<?php

class OrderHelper extends Helper
{

    private $credit_rule;
    private $owner_rule;
    private $car_rule;
    private $gps_rule;
    private $cert_fields;
    private $spouse_rule;
    private $guarantor_rule;
    private $modify_fields;
    protected $loan_mode;
    protected $mode;
    protected $attach_key;

    public function __construct()
    {
        $this->gps_rule = array(
            'ot_gps_install' => array('require', 'gps安装时间不能为空'),
            'ot_gps_no' => array('require', 'gps序列号不能为空'),
        );
        $this->base_rule = array(
            'o_business_uid' => array('require', '业务来源人不能为空'),
            'o_buyer_type' => array('require', '经销商类型不能为空'),
            'o_buyer_id' => array('require', '请选择经销商'),
            'o_buyer' => array('require', '请选择经销商'),
        );
        $this->credit_rule = array(
            'o_bank_id' => array('number', '贷款银行不能为空'),
            'o_vip_name' => array('require', '客户姓名不能为空'),
            'o_vip_card' => array('idcard', '客户身份证错误'),
        );
        $this->owner_rule = array(
            'ot_edu' => array('require', '学历不能为空'),
            'ot_residence_pro' => array('require', '户籍所在省份不能为空'),
            'ot_residence_city' => array('require', '户籍所在市不能为空'),
            'ot_residence_area' => array('require', '户籍所在区域不能为空'),
            'ot_mobile' => array('mobile', '手机号错误'),
            'ot_married' => array('require', '婚否不能为空'),
            'ot_bankcard' => array('require', '银行卡号不能为空'),
            //'ot_liveadd' => array('require', '邮寄地址不能为空'),
            'ot_tel' => array('require', '固定电话不能为空'),
            //'ot_home_add' => array('require', '实际家庭住址不能为空'),
            'ot_house_add' => array('require', '房产地址不能为空'),
            'ot_house_owner' => array('require', '房屋所有权人不能为空'),
            'ot_hown_relation' => array('require', '房屋所有权人与购车人关系不能为空'),
            'ot_house_nature' => array('require', '房产性质不能为空'),
            'ot_house_acreage' => array('number', '房屋面积错误'),
            'ot_house_price' => array('number', '房屋市价错误'),
            'ot_house_loan' => array('number', '房贷金额错误'),
            'ot_house_loyear' => array('number', '房贷年限错误'),
            'ot_house_refundmo' => array('number', '房贷月还款错误'),
            'ot_company' => array('require', '公司名不能为空'),
            //'ot_company_add' => array('require', '单位地址不能为空'),
            'ot_company_tel' => array('require', '单位电话不能为空'),
            'ot_company_type' => array('require', '单位类型不能为空'),
            'ot_duty_type' => array('require', '职务类型不能为空'),
            'ot_duty' => array('require', '职务不能为空'),
            'ot_operat_period' => array('require', '经验期限不能为空'),
            'ot_seniority' => array('require', '工龄不能为空'),
            'ot_stake' => array('require', '所占股份不能为空'),
            'ot_income_month' => array('require', '月收入不能为空'),
        );
        $this->car_rule = array(
            'ot_car_type' => array('require', '车辆类型不能为空'),
            'ot_car_model' => array('require', '车辆型号不能为空'),
            'ot_car_seating' => array('number', '座位数值错误'),
            'ot_car_pose' => array('require', '车型构成不能为空'),
            'ot_pubbrand' => array('require', '是否公牌不能为空'),
            'ot_reg_province' => array('require', '上牌地省份不能为空'),
            'ot_reg_city' => array('require', '上牌地市不能为空'),
            'ot_reg_area' => array('require', '上牌地区域不能为空'),
            'ot_car_owners' => array('require', '行驶证车主不能为空'),
            'ot_loan_year' => array('number', '贷款年限不能为空'),
            'ot_loan_type' => array('require', '产品类型不能为空'),
            'ot_car_price' => array('require', '车价错误'),
            'ot_loan_limit' => array('number', '贷款额度错误'),
            'ot_loan_rate' => array('number', '公司费率错误'),
            'ot_bankrt_id' => array('require', '银行产品代码错误'),
            'ot_bankrt_code' => array('require', '银行产品代码错误'),
        );
        $this->cert_fields = array('ct_id', 'ct_oid', 'ct_key', 'ct_attach', 'ct_sign', 'ct_video', 'ct_name', 'ct_code', 'ct_sex', 'ct_birth', 'ct_affiliation', 'ct_idaddress', 'ct_validity_start', 'ct_validity_end', 'ct_issue', 'ct_remark', 'ct_results', 'ct_detail', 'ct_dateline', 'ct_skip','ct_guarantor_type','ct_status', 'ct_mobile','ct_bigdata','ct_bigdata_number','ct_querytime','ct_bigdata_org','ct_previous_remark','ct_previous_querytime','ct_bairong_result','ct_fico_result');
        $this->spouse_rule = array(
            'ct_spouse_degree' => array('require', '配偶学历不能为空'),
            'ct_spouse_province' => array('require', '户籍城市不能为空'),
            'ct_spouse_city' => array('require', '户籍省份不能为空'),
            'ct_spouse_area' => array('require', '户籍地区不能为空'),
            'ct_spouse_mobile' => array('mobile', '配偶手机号错误'),
            'ct_spouse_liveadd' => array('require', '现居地不能为空'),
            'ct_spouse_tel' => array('require', '固定电话不能为空'),
        );
        $this->guarantor_rule = array(
            'ct_guarantor_degree' => array('require', '担保人学历不能为空'),
            'ct_guarantor_province' => array('require', '户籍城市不能为空'),
            'ct_guarantor_city' => array('require', '户籍省份不能为空'),
            'ct_guarantor_area' => array('require', '户籍地区不能为空'),
            'ct_guarantor_mobile' => array('mobile', '担保人手机号错误'),
        );
        $this->modify_fields = array(
            'order' => array(
                'o_buyer_type' => array('经销商类别', 1, '经销商类别'),
                'o_buyer' => array('经销商', 1),
            ),
            'order_owner' => array(
                'ot_edu' => array('学历', 1, '学历'),
                'ot_mobile' => array('手机号', 0),
                'ot_married' => array('婚否', 1, '婚姻状况'),
                'ot_liveadd' => array('邮寄地址', 0),
                'ot_tel' => array('固定电话', 0),
                'ot_house_add' => array('房产地址', 0),
                'ot_house_owner' => array('所有权人', 0),
                'ot_hown_relation' => array('与购车人关系', 1, '关系'),
                'ot_house_nature' => array('房屋性质', 0),
                'ot_house_acreage' => array('房屋面积', 0),
                'ot_house_price' => array('目前市价', 0),
                'ot_house_loan' => array('房贷金额', 0),
                'ot_house_loyear' => array('房贷年限(月)', 0),
                'ot_house_refundmo' => array('月还款额', 0),
                'ot_company' => array('公司名称', 0),
                'ot_company_add' => array('单位类型', 1, '行业'),
                'ot_duty_type' => array('职务类别', 1, '职务类别'),
                'ot_duty' => array('职务', 1, '职业或职务'),
                'ot_operat_period' => array('经营期限', 1, '经营期限'),
                'ot_income_month' => array('月收入', 0),
                'ot_company_add' => array('单位地址', 0),
                'ot_seniority' => array('工龄', 1, '工龄'),
                'ot_stake' => array('所占股份', 0),
                'ot_company_tel' => array('单位电话', 0),
                'ot_bankcard' => array('流水卡号',0)
            ),
            'guarantor' => array(
                'ct_guarantor_degree' => array('学历', 1, '学历'),
                'ct_guarantor_mobile' => array('手机号', 0),
                'ct_guarantor_married' => array('婚否', 1, '婚姻状况'),
                'ct_guarantor_liveadd' => array('现住地址', 0),
                'ct_guarantor_headd' => array('房产地址', 0),
                'ct_guarantor_howner' => array('所有权人', 0),
                'ct_guarantor_hrelation' => array('与购车人关系', 1, '关系'),
                'ct_guarantor_hnature' => array('房屋性质', 0),
                'ct_guarantor_hacreage' => array('房屋面积', 0),
                'ct_guarantor_hprice' => array('目前市价', 0),
                'ct_guarantor_hloan' => array('房贷金额', 0),
                'ct_guarantor_hloyear' => array('房贷年限(月)', 0),
                'ct_guarantor_hrefundmo' => array('月还款额', 0),
                'ct_guarantor_company' => array('公司名称', 0),
                'ct_guarantor_ctype' => array('单位类型', 1, '行业'),
                'ct_guarantor_dutytp' => array('职务类别', 1, '职务类别'),
                'ct_guarantor_duty' => array('职务', 1, '职业或职务'),
                'ct_guarantor_operatpd' => array('经营期限', 1, '经营期限'),
                'ct_guarantor_mincome' => array('月收入', 0),
                'ct_guarantor_cadd' => array('单位地址', 0),
                'ct_guarantor_seniority' => array('工龄', 1, '工龄'),
                'ct_guarantor_stake' => array('所占股份', 0),
                'ct_guarantor_ctel' => array('单位电话', 0)
            ),
            'spouse' => array(
                'ct_spouse_degree' => array('学历', 1 , '学历'),
                'ct_spouse_mobile' => array('手机号', 0),
                'ct_spouse_liveadd' => array('现住地址', 0),
                'ct_spouse_tel' => array('固定电话', 0),
                'ct_spouse_company' => array('公司名称', 0),
                'ct_spouse_cadd' => array('单位地址', 0),
                'ct_spouse_ctype' => array('单位类型', 1, '行业'),
                'ct_spouse_ctel' => array('单位电话', 0)
                ),
            'order_car' => array(
                'ot_car_model' => array('车型', 1),
                'ot_car_seating' => array('座位', 0),
                'ot_pubbrand' => array('是否公牌', 1),
                'ot_car_owners' => array('行驶证车主', 0),
            ),
        );
        $mode = Config::GetCommon();
        $this->mode = $mode;
        $this->loan_mode = $mode['mode'];
    }

    /**
     * 征信录入
     * @param type $data
     * @param type $where
     * @return type
     */
    public function orderSave($data, $where = '')
    {
        if (is_numeric($where)) {
            $where = array('`o_id` = ?' => $where);
        }
        $check_data = $this->checkData($data);
        if (!$check_data['success']) {
            return $check_data;
        }
        $model = $this->LoadModel('Public');
        $model->beginTransaction();
        try {
            if (empty($where)) {
                if (isset($data['o_branch_type']) && $data['o_branch_type'] == 'dot') {
                    $branch = $model->getOneRow('branch', array('br_model'), array('`br_id` = ?' => $data['o_branch_id']));
                    switch ($branch['br_model']) {
                        case '普通':
                            $data['o_pre_mode'] = 1;
                            break;
                        case '预审':
                            $data['o_pre_mode'] = 2;
                            break;
                        case '超级预审':
                            $data['o_pre_mode'] = 3;
                            break;
                    }
                }
                $data['o_number'] = $this->makeSn($data['o_uid']);
                $data['o_add_time'] = NOW_TIME;
                $data['o_sell_time'] = NOW_TIME;
                $base_url = \yii2api\Config::$base_url;
                $uri = 'big_data/validate/fico-score';
                $id = $model->save('order', $data);
                file_put_contents(YII2API_PHP_SDK_DIR . "/yii2api/logs/credit_data.log", "\n\n\n" . date("Y-m-d H:i:s") . "\n" . var_export($check_data, true) . "\n", FILE_APPEND);
                foreach ($check_data['data'] as $key => $val) {
                    if (!empty($val)) {
                        foreach ($val as $k => $v) {
                            //$ct_affiliation = $this->getCardrt($v['ct_code']);
                            $cert_data = array(
                                'ct_oid' => $id,
                                'ct_key' => $key,
                                'ct_attach' => serialize($v['ct_attach']),
                                'ct_name' => $v['ct_name'],
                                'ct_code' => $v['ct_code'],
                                'ct_sex' => $v['ct_sex'],
                                'ct_birth' => $v['ct_birth'],
                                'ct_mobile' => $v['ct_mobile'],
                                'ct_idaddress' => $v['ct_idaddress'],
                                'ct_affiliation' => $v['ct_affiliation'],
                                'ct_validity_start' => $v['ct_validity_start'],
                                'ct_validity_end' => $v['ct_validity_end'],
                                'ct_issue' => $v['ct_issue'],
                                'ct_attach' => serialize($v['ct_attach']),
                                'ct_dateline' => NOW_TIME,
                            );
                            if (isset($v['ct_guarantor_type'])&&$v['ct_guarantor_type']){
                                $cert_data['ct_guarantor_type'] = $v['ct_guarantor_type'];
                            }
                            //fico大数据
                            $header = \yii2api\classes\components\auth\Auth::getHeader();
                            $body = array(
                                'mobile' => $v['ct_mobile'],
                                'idcard' => $v['ct_code']
                            );
                            $reponse = \Httpful\Request::post($base_url.$uri)->body($body)->sendsType(\Httpful\Mime::FORM)->addHeaders($header)->send();
                            $cert_data['ct_fico_result'] = serialize($this->object2array_pre($reponse->body->data));
                            $cert_id = $model->save('order_cert', $cert_data);
                            foreach ($v['ct_attach'] as $ik => $iv) {
                                $model->update('attach_image', array('ai_no' => $cert_id), array('`ai_path` = ?' => $iv));
                            }
                            $relation_arr = array('vip' => '本人', 'spouse' => '配偶', 'guarantor' => '担保人');
                            $credit_data = array(
                                'user_id' => $id,
                                'bairong_validate' => 1,
                                'bank_name'=>$data['o_bank'],
                                'orderno' => '!ysjr' . substr((1000000000000 + $id), 1, 12),
                                'master_name' => $data['o_vip_name'],
                                'custom_name' => $v['ct_name'],
                                'relation' => $relation_arr[$key],
                                'idtype' => '000',
                                'idno' => $v['ct_code'],
                                'mobile' => $v['ct_mobile'],
                                'pics' => array(
                                    array(
                                        'picid' => '0002',
                                        'picurl' => StringCode::doUrlimage($v['ct_attach']['fcard']),
                                    ),
                                    array(
                                        'picid' => '0003',
                                        'picurl' => StringCode::doUrlimage($v['ct_attach']['rcard']),
                                    ),
                                    array(
                                        'picid' => '0001',
                                        'picurl' => StringCode::doUrlimage($v['ct_attach']['auth']),
                                    ),
                                    array(
                                        'picid' => '0004',
                                        'picurl' => StringCode::doUrlimage($v['ct_attach']['sign']),
                                    ),
                                ),
                            );
                            //if ($data['o_bank'] == '中国工商银行股份有限公司杭州延中支行' || $data['o_bank'] == '（2017）中国工商银行股份有限公司杭州延中支行'):
                               // $credit_data['bank_sign_code'] = \yii2api\Config::$bank['icbc_bank_sign_code'];
                                //
                            $x = \yii2api\classes\yii2api\Bank::submitCredit($credit_data);
                            if ($x->msg_code == '2001') {
                                //请将上一次的征信结果，直接保存order_cert表
                            }
                            if ($x->msg_code == '2002') {
                                $model->update('order_cert', array('ct_remark' => '银行灰名单客户', 'ct_results' => '已查询'), array('`ct_id` = ?' => $cert_id));
                            }
                            file_put_contents(YII2API_PHP_SDK_DIR . "/yii2api/logs/api_back_data.log", "\n\n\n" . date("Y-m-d H:i:s") . "\n" . var_export($x, true) . "\n", FILE_APPEND);
                            $this->updateBigDataforOrdercert($cert_id, $x);
                            //endif;
                        }
                    }
                }
                //日志保存
                $log_data = array(
                    'log_uid' => $data['o_uid'],
                    'log_action' => 'add',
                    'log_related_id' => $id,
                    'log_explain' => '征信录入',
                    'log_dateline' => NOW_TIME,
                );
                $model->save('order_log', $log_data);
                $model->commit();
                return array('success' => true, 'msg' => $id);
            } else {
                $model->update('order', $data, $where);
                $model->commit();
                return array('success' => true);
            }
        } catch (Exception $ex) {
            $model->rollBack();
            return array('success' => false, 'msg' => '保存异常:' . $ex->getMessage());
        }
    }

    /**
     * 征信提交
     * @param type $oid
     * @return boolean
     */
    public function creditSubmit($oid, $uid = 0)
    {
        $model = $this->LoadModel('Public');
        $cert = $model->getList('order_cert', '*', array('`ct_oid` = ?' => $oid, '`ct_status` = ?' => 'ok', '`ct_results` = ?' => '未查询'));
        if (empty($cert)) {
            $model->beginTransaction();
            try {
                //更新订单状态
                $model->update('order', array('o_status' => '征信查询', 'o_search_time' => NOW_TIME), array('`o_id` = ?' => $oid));
                //生成快递记录
                $model->update('logistics', array('ls_status' => 'del'), array('ls_oid' => $oid));
                $model->save('logistics', array('ls_oid' => $oid, 'ls_status' => 'no'));
                //日志保存
                $log_data = array(
                    'log_uid' => $uid,
                    'log_action' => 'credit_submit',
                    'log_related_id' => $oid,
                    'log_explain' => '征信提交',
                    'log_dateline' => NOW_TIME,
                );
                $model->save('order_log', $log_data);
                $model->commit();
                return array('success' => true, 'msg' => $id);
            } catch (Exception $ex) {
                $model->rollBack();
                return array('success' => false, 'msg' => '保存异常');
            }
        } else {
            return array('success' => false, 'msg' => '征信查询未全部提交');
        }
    }

    public function getSexBirthAffiliationFromIDCard($card){
        $affi = $this->getCardrt($card, 'str');
        if(empty($affi)){
            return array();
        }else{
            $birth = substr($card, 6, 8);
            if (15 == strlen($card)) {
                $sex = substr($card, 15, 1)%2==0?'女':'男';
            }else{
                $sex = substr($card, 16, 1)%2==0?'女':'男';
            }
            return array(
                'affiliation'  => $affi,
                'birth' => $birth,
                'sex' => $sex
            );
        }
    }

    /**
     * 录入数据校验
     * @param type $data
     * @return boolean
     */
    public function checkData($data)
    {
        $idcard = array();
        $validator = Validator::checkRule($data, $this->credit_rule);
        if (!$validator['pass']) {
            return array('success' => false, 'msg' => $validator['msg']);
        }
        if (!Validator::isIdcard($data['o_vip_card'])) {
            return array('success' => false, 'msg' => '客户身份证错误');
        }
        if (!$this->idcardCheck($data['o_vip_card'])) {
            return array('success' => false, 'msg' => "当前主贷人身份证{$data['o_vip_card']}在180个自然日内已存在申请或担保或已被加入黑名单");
        }

        if (empty($data['o_vip_fcard'])) {
            return array('success' => false, 'msg' => '请上传客户正面身份证');
        }

        if (empty($data['o_vip_rcard'])) {
            return array('success' => false, 'msg' => '请上传客户反面身份证');
        }

        if (empty($data['o_vip_auth'])) {
            return array('success' => false, 'msg' => '请上传客户授权书');
        }

        if (empty($data['o_vip_sign'])) {
            return array('success' => false, 'msg' => '请上传客户签名');
        }

        $cardinfo = $this->getSexBirthAffiliationFromIDCard($data['o_vip_card']);
        if(empty($cardinfo))
            $cardinfo = array(
                'affiliation'  => '',
                'birth' => $data['o_vip_birth'],
                'sex' => $data['o_vip_sex']
            );
        $cert['vip'][] = array(
            'ct_name' => $data['o_vip_name'],
            'ct_code' => $data['o_vip_card'],
            'ct_sex' => $cardinfo['sex'],
            'ct_birth' => $cardinfo['birth'],
            'ct_affiliation' => $cardinfo['affiliation'],
            'ct_idaddress' => $data['o_vip_idaddress'],
            'ct_validity_start' => $data['o_vip_validity_start'],
            'ct_validity_end' => $data['o_vip_validity_end'],
            'ct_issue' => $data['o_vip_issue'],//发证单位
            'ct_mobile' => $data['o_vip_mobile'],
            'ct_attach' => array(
                'fcard' => $data['o_vip_fcard'],
                'rcard' => $data['o_vip_rcard'],
                'auth' => $data['o_vip_auth'],
                'sign' => $data['o_vip_sign'],
            ),
        );
        $idcard[] = $data['o_vip_card'];
        if (!empty($data['o_spouse_name'])) {
            if (!Validator::isIdcard($data['o_spouse_card'])) {
                return array('success' => false, 'msg' => '配偶身份证错误');
            }

            //判断配偶性别是否和主贷人性别一样
            $vip_sex = substr($data['o_vip_card'], (strlen($data['o_vip_card']) == 15 ? -1 : -2), 1) % 2 ? '男' : '女';
            $spouse_sex = substr($data['o_spouse_card'], (strlen($data['o_spouse_card']) == 15 ? -1 : -2), 1) % 2 ? '男' : '女';
            if ($vip_sex == $spouse_sex) {
                return array('success' => false, 'msg' => '主贷人与配偶性别一致');
            }

            if (!$this->idcardCheck($data['o_spouse_card'])) {
                return array('success' => false, 'msg' => "当前配偶身份证{$data['o_spouse_card']}在180个自然日内已存在申请或担保或已被加入黑名单");
            }
            if (empty($data['o_spouse_fcard'])) {
                return array('success' => false, 'msg' => '请上传配偶正面身份证');
            }

            if (empty($data['o_spouse_rcard'])) {
                return array('success' => false, 'msg' => '请上传配偶反面身份证');
            }

            if (empty($data['o_spouse_auth'])) {
                return array('success' => false, 'msg' => '请上传配偶授权书');
            }

            if (empty($data['o_spouse_sign'])) {
                return array('success' => false, 'msg' => '请上传配偶签名');
            }

            $cardinfo = $this->getSexBirthAffiliationFromIDCard($data['o_spouse_card']);
            if(empty($cardinfo))
                $cardinfo = array(
                    'affiliation'  => '',
                    'birth' => $data['o_spouse_birth'],
                    'sex' => $data['o_spouse_sex']
                );
            $cert['spouse'][] = array(
                'ct_name' => $data['o_spouse_name'],
                'ct_code' => $data['o_spouse_card'],
                'ct_sex' => $cardinfo['sex'],
                'ct_birth' => $cardinfo['birth'],
                'ct_affiliation' => $cardinfo['affiliation'],
                'ct_idaddress' => $data['o_spouse_idaddress'],
                'ct_validity_start' => $data['o_spouse_validity_start'],
                'ct_validity_end' => $data['o_spouse_validity_end'],
                'ct_issue' => $data['o_spouse_issue'],
                'ct_mobile' => $data['o_spouse_mobile'],
                'ct_attach' => array(
                    'fcard' => $data['o_spouse_fcard'],
                    'rcard' => $data['o_spouse_rcard'],
                    'auth' => $data['o_spouse_auth'],
                    'sign' => $data['o_spouse_sign'],
                ),
            );
            $idcard[] = $data['o_spouse_card'];
        }
        if (!empty($data['o_guarantor_name'])) {
            foreach ($data['o_guarantor_name'] as $key => $val) {
                if (!Validator::isIdcard($data['o_guarantor_card'][$key])) {
                    return array('success' => false, 'msg' => '担保人身份证错误');
                }

                if (!$this->idcardCheck($data['o_guarantor_card'][$key])) {
                    return array('success' => false, 'msg' => "当前担保人身份证{$data['o_guarantor_card'][$key]}在180个自然日内已存在申请或担保或已被加入黑名单");
                }
                if (empty($data['o_guarantor_fcard'][$key])) {
                    return array('success' => false, 'msg' => '请上传担保人正面身份证');
                }

                if (empty($data['o_guarantor_rcard'][$key])) {
                    return array('success' => false, 'msg' => '请上传担保人反面身份证');
                }

                if (empty($data['o_guarantor_auth'][$key])) {
                    return array('success' => false, 'msg' => '请上传担保人授权书');
                }

                if (empty($data['o_guarantor_sign'][$key])) {
                    return array('success' => false, 'msg' => '请上传担保人签名');
                }

                $cardinfo = $this->getSexBirthAffiliationFromIDCard($data['o_guarantor_card'][$key]);
                if(empty($cardinfo))
                    $cardinfo = array(
                        'affiliation'  => '',
                        'birth' => $data['o_guarantor_birth'][$key],
                        'sex' => $data['o_guarantor_sex'][$key]
                    );

                $_x3 = array(
                    'ct_name' => $data['o_guarantor_name'][$key],
                    'ct_code' => $data['o_guarantor_card'][$key],
                    'ct_sex' => $cardinfo['sex'],
                    'ct_birth' => $cardinfo['birth'],
                    'ct_affiliation' => $cardinfo['affiliation'],
                    'ct_idaddress' => $data['o_guarantor_idaddress'][$key],
                    'ct_validity_start' => $data['o_guarantor_validity_start'][$key],
                    'ct_validity_end' => $data['o_guarantor_validity_end'][$key],
                    'ct_issue' => $data['o_guarantor_issue'][$key],
                    'ct_mobile' => $data['o_guarantor_mobile'][$key],
                    'ct_attach' => array(
                        'fcard' => $data['o_guarantor_fcard'][$key],
                        'rcard' => $data['o_guarantor_rcard'][$key],
                        'auth' => $data['o_guarantor_auth'][$key],
                        'sign' => $data['o_guarantor_sign'][$key],
                    ),
                );
                if (isset($data['ct_guarantor_type'][$key])&&$data['ct_guarantor_type'][$key]){
                    $_x3['ct_guarantor_type'] = $data['ct_guarantor_type'][$key];
                }
                $cert['guarantor'][] = $_x3;
                $idcard[] = $data['o_guarantor_card'][$key];
            }
        }
        if (count($idcard) != count(array_unique($idcard))) {
            return array('success' => false, 'msg' => '身份证号有重复');
        }

        //同步查询老系统中是否有身份证号重复
        //2018.3.12去掉老系统查重
        //$this->LoadResurces('oldapi/class.carloan');
        //$carloan = new Carloan();
        //$card_check = $carloan->cardCheck($idcard);
        //$card_check = json_decode($card_check, true);
        //if (!$card_check['success']) {
        //    return array('success' => false, 'msg' => $card_check['msg']);
        //}

        return array('success' => true, 'msg' => '', 'data' => $cert);
    }

    /**
     * 身份证校验
     * @param type $card
     * @return boolean
     */
    public function idcardCheck($idno)
    {
        $model = $this->LoadModel('Public');
        $blackcheck = $model->getOneRow('blacklist', array('bl_id'), array('`bl_card` = ?' => $idno, '`bl_status` = ?' => 'ok'));
        if (!empty($blackcheck)) {
            return false;
        }
        //180天内是否有担保和申请
        $certcheck = $model->getOneRow('order_cert', array('ct_id'), array('`ct_code` = ?' => $idno, '`ct_status` = ?' => 'ok', '`ct_dateline` >= ?' => NOW_TIME - 15552000, '`ct_skip` = ?' => 0));
        if (!empty($certcheck)) {
            return false;
        }
        return true;
    }

    /**
     * 生成订单号
     * @return type
     */
    public function makeSn($uid)
    {
        $model = $this->LoadModel('Public');
        $member = $model->getOneRow('member', '*', array('`u_id` = ?' => $uid));
        switch ($member['u_dp_type']) {
            case 'dp': //部门
                $department = $model->getOneRow('department', array('dp_code'), array('`dp_id` = ?' => $member['u_dp_id']));
                $code = $department['dp_code'];
                break;
            case 'dot': //网点
                $branch = $model->getOneRow('branch', array('br_code'), array('`br_id` = ?' => $member['u_dp_id']));
                $code = $branch['br_code'];
                break;
            case 'rg': //大区
                $region = $model->getOneRow('region', array('rg_code'), array('`rg_id` = ?' => $member['u_dp_id']));
                $code = $region['rg_code'];
                break;
        }
        $today_max = $model->getRowCount('order', array('`o_add_time` >= ?' => strtotime(date('Y-m-d')), 'LOCATE(?, `o_number`) > 0' => $code));
        $today_max = empty($today_max) || $today_max == null ? 1 : $today_max + 1;
        $today_max = substr(strval($today_max + 1000), 1, 3);
        $sn = $code . '-' . date('ymd') . '-' . $today_max;
        return $sn;
    }

    /**
     * 初审单录入
     * @param type $data
     */
    public function trialOrder($data)
    {
        $validator = Validator::checkRule($data['baseorder'], $this->base_rule);
        if (!$validator['pass']) {
            return array('success' => false, 'msg' => $validator['msg']);
        }
        $validator = Validator::checkRule($data['owner'], $this->owner_rule);
        if (!$validator['pass']) {
            return array('success' => false, 'msg' => $validator['msg']);
        }
        $validator = Validator::checkRule($data['car'], $this->car_rule);
        if (!$validator['pass']) {
            return array('success' => false, 'msg' => $validator['msg']);
        }
        if (!empty($data['cert'])) {
            foreach ($data['cert'] as $k => $v) {
                if (!empty($v)) {
                    foreach ($v as $key => $val) {
                        if ($k == 'spouse') {
                            $validator = Validator::checkRule($val['ct_detail'], $this->spouse_rule);
                            if (!$validator['pass']) {
                                return array('success' => false, 'msg' => $validator['msg']);
                            }
                        } else {
                            $validator = Validator::checkRule($val['ct_detail'], $this->guarantor_rule);
                            if (!$validator['pass']) {
                                return array('success' => false, 'msg' => $validator['msg']);
                            }
                        }
                    }
                }

            }
        }

        $model = $this->LoadModel('Public');
        $model->beginTransaction();
        $order_row = $model->getOneRow('order', '*', array('`o_id` = ?' => $data['oid']));
        try {
            if ($data['cert']) {
                foreach ($data['cert'] as $k => $v) {
                    if (!empty($v)) {
                        foreach ($v as $key => $val) {
                            $model->update('order_cert', array('ct_detail' => serialize($val['ct_detail'])), array('`ct_id` = ?' => $val['ct_id']));
                        }
                    }

                }
            }
            $model->update('order_cert',array('ct_mobile' => $data['owner']['ot_mobile'],'ct_idaddress' => $data['vip']['ct_idaddress'],'ct_issue' => $data['vip']['ct_issue'],'ct_validity_end' => $data['vip']['ct_validity_end']),array('`ct_oid` = ?' => $data['oid'],'`ct_key` = ?' =>'vip'));
            if(isset($data['ct_spouse_detail'])){
                $model->update('order_cert',array('ct_mobile' => $data['ct_spouse_detail']['ct_spouse_mobile']),array('`ct_oid` = ?' => $data['oid'],'`ct_key` = ?' =>'spouse'));
            }
            if(isset($data['ct_guarantor_detail'])){
                for($i = 0;$i<count($data['ct_guarantor_detail']);$i++){
                    $model->update('order_cert',array('ct_mobile' => $data['ct_guarantor_detail'][$i]['ct_guarantor_mobile'],'ct_guarantor_type' => $data['ct_guarantor_detail'][$i]['ct_guarantor_type']),array('`ct_id` = ?' => $data['ct_guarantor_detail'][$i]['ct_guarantor_id']));
                }
            }

            $check = $model->getOneRow('order_owner', array('ot_id'), array('`ot_oid` = ?' => $data['oid']));

            $data['owner']['ot_status'] = 'ok';
            $data['owner']['ot_oid'] = $data['oid'];
            $data['owner']['ot_dateline'] = NOW_TIME;
            if (empty($check)) {
                $model->save('order_owner', $data['owner']);
            } else {
                $model->update('order_owner', $data['owner'], array('`ot_oid` = ?' => $data['oid']));
            }

            $data['car']['ot_status'] = 'ok';
            $data['car']['ot_oid'] = $data['oid'];
            $data['car']['ot_dateline'] = NOW_TIME;
            $check = $model->getOneRow('order_car', array('ot_id'), array('`ot_oid` = ?' => $data['oid']));
            if (empty($check)) {
                $model->save('order_car', $data['car']);
            } else {
                $data['car']['ot_status'] = 'ok';
                $model->update('order_car', $data['car'], array('`ot_oid` = ?' => $data['oid']));
            }

            $data['attachment']['oa_status'] = 'ok';
            $data['attachment']['oa_oid'] = $data['oid'];
            $data['attachment']['oa_dateline'] = NOW_TIME;
            $check = $model->getOneRow('order_attachment', array('oa_id'), array('`oa_oid` = ?' => $data['oid']));
            if (empty($check)) {
                $model->save('order_attachment', $data['attachment']);
            } else {
                $data['attachment']['oa_status'] = 'ok';
                $model->update('order_attachment', $data['attachment'], array('`oa_oid` = ?' => $data['oid']));
            }
            //
            $data['baseorder']['o_status'] = '初审提交';
            $data['baseorder']['o_first_time'] = NOW_TIME;
            $data['baseorder']['o_loan_money'] = $data['car']['ot_loan_limit']; //同步贷款金额
            //设置审核优先级
            if($data['car']['ot_loan_limit']<=80000){
                $data['baseorder']['o_audit_priority'] = 3;
            }else{
                $data['baseorder']['o_audit_priority'] = 1;
            }
            if(empty($order_row['o_bank_time'])){
                $data['baseorder']['o_bank_time'] = NOW_TIME;
            }  //银行利率确定日期
            //资审占位
            $fto_msg = $this->ftoPerch($data['oid']);
            $data['baseorder']['o_perch'] = $fto_msg['o_perch'];
            $data['baseorder']['o_perch_name'] = $fto_msg['o_perch_name'];

            $model->update('order', $data['baseorder'], array('`o_id` = ?' => $data['oid']));
            //
            $model->delete('order_index', array('`ot_id` = ?' => $data['oid']));
            $model->save('order_index', array('ot_id' => $data['oid'], 'ot_type' => '资料审核', 'ot_dateline' => NOW_TIME));
            if ($data['baseorder']['o_pre_mode'] != 1) {
                $model->save('order_index', array('ot_id' => $data['oid'], 'ot_type' => '层级审核', 'ot_dateline' => NOW_TIME));
            }
            //日志保存
            $log_data = array(
                'log_uid' => $data['uid'],
                'log_action' => 'torder_submit',
                'log_related_id' => $data['oid'],
                'log_explain' => '初审单录入提交',
                'log_dateline' => NOW_TIME,
            );
            $model->save('order_log', $log_data);
            //增加同步任务
            $model->save('task', array(
                'task_type' => 'ordersync',
                'task_releid' => $data['oid'],
                'task_addtime' => NOW_TIME,
            ));
            $model->save('task', array(
                'task_type' => 'ordersort',
                'task_releid' => $data['oid'],
                'task_addtime' => NOW_TIME,
            ));
            $model->commit();
            $this->telPerch($data['oid'],'submit');
            return array('success' => true, 'msg' => '保存成功');
        } catch (Exception $ex) {
            $model->rollBack();
            return array('success' => false, 'msg' => '保存异常');
        }
    }

    /**
     * 初审单仅保存
     * @param type $data
     * @return type
     */
    public function trialOrderSave($data)
    {
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order','*',array('`o_id` =?' =>$data['oid']));
        if(!in_array($order_row['o_status'],array('征信提交','征信查询'))){
            return array('success' => false, 'msg' => '订单已提交,无法进行保存');
        }
        $model->beginTransaction();
        try {
            if ($data['cert']) {
                foreach ($data['cert'] as $k => $v) {
                    if (!empty($v)) {
                        foreach ($v as $key => $val) {
                            $_a = array('ct_detail' => serialize($val['ct_detail']));
                            $model->update('order_cert', $_a, array('`ct_id` = ?' => $val['ct_id']));
                        }
                    }
                }
            }
            $data['vip']['ct_mobile'] = $data['owner']['ot_mobile'];
            $model->update('order_cert',$data['vip'], array('`ct_oid` = ?' => $data['oid'],'`ct_key` = ?' =>'vip'));
            
            $_t = array();
            if(isset($data['ct_spouse_detail'])){
                $_t['ct_mobile'] = $data['ct_spouse_detail']['ct_mobile'] = $data['ct_spouse_detail']['ct_spouse_mobile'];
                $_t['ct_detail'] = serialize($data['ct_spouse_detail']);
                $model->update('order_cert',$_t,array('`ct_oid` = ?' => $data['oid'],'`ct_key` = ?' =>'spouse'));
            }
            if(!empty($data['ct_guarantor_detail'])){
                foreach ($data['ct_guarantor_detail'] as $k => $v){
                    $_t = array();
                    $_t['ct_mobile'] = $v['ct_mobile'] = $v['ct_guarantor_mobile'];
                    $model->update('order_cert', $_t ,array('`ct_id` = ?' => $v['ct_id']));
                    if($v['ct_guarantor_type'])$model->update('order_cert',array('ct_guarantor_type' => $v['ct_guarantor_type']),array('`ct_id` = ?' => $v['ct_guarantor_id']));
                }
            }
            
            $check = $model->getOneRow('order_owner', array('ot_id'), array('`ot_oid` = ?' => $data['oid']));
            $data['owner']['ot_status'] = 'draft';
            $data['owner']['ot_oid'] = $data['oid'];
            $data['owner']['ot_dateline'] = NOW_TIME;
            if (empty($check)) {
                $model->save('order_owner', $data['owner']);
            } else {
                $model->update('order_owner', $data['owner'], array('`ot_id` = ?' => $check['ot_id']));
            }
            $check = $model->getOneRow('order_car', array('ot_id'), array('`ot_oid` = ?' => $data['oid']));
            $data['car']['ot_status'] = 'draft';
            $data['car']['ot_oid'] = $data['oid'];
            $data['car']['ot_dateline'] = NOW_TIME;
            unset($data['car']['ot_assessment']);
            if (empty($check)) {
                $model->save('order_car', $data['car']);
            } else {
                $model->update('order_car', $data['car'], array('`ot_id` = ?' => $check['ot_id']));
            }
            $check = $model->getOneRow('order_attachment', array('oa_id'), array('`oa_oid` = ?' => $data['oid']));
            $data['attachment']['oa_status'] = 'draft';
            $data['attachment']['oa_oid'] = $data['oid'];
            $data['attachment']['oa_dateline'] = NOW_TIME;
            if (empty($check)) {
                $model->save('order_attachment', $data['attachment']);
            } else {
                $model->update('order_attachment', $data['attachment'], array('`oa_oid` = ?' => $data['oid']));
            }
            $model->update('order', $data['baseorder'], array('`o_id` = ?' => $data['oid']));
            //日志保存
            $log_data = array(
                'log_uid' => $data['uid'],
                'log_action' => 'torder_draft',
                'log_related_id' => $data['oid'],
                'log_explain' => '初审单草稿保存',
                'log_dateline' => NOW_TIME,
            );
            $model->save('order_log', $log_data);
            $model->commit();
            return array('success' => true, 'msg' => '保存成功');
        } catch (Exception $ex) {
            $model->rollBack();
            return array('success' => false, 'msg' => '保存异常' . $ex->getMessage());
        }
    }

    /**
     * 担保人补录
     * @param type $data array('o_id' => '', 'o_guarantor_name' => '' ...)
     * @return type
     */
    public function guarantorUp($data)
    {
        $base_url = \yii2api\Config::$base_url;
        $uri = 'big_data/validate/fico-score';
        foreach ($data['o_guarantor_name'] as $key => $val) {
            $idcard[] = $data['o_guarantor_card'][$key];
            if (!Validator::isIdcard($data['o_guarantor_card'][$key])) {
                return array('success' => false, 'msg' => '担保人身份证错误');
            }

            if (!$this->idcardCheck($data['o_guarantor_card'][$key])) {
                return array('success' => false, 'msg' => "当前担保人身份证{$data['o_guarantor_card'][$key]}在180个自然日内已存在申请或担保或已被加入黑名单");
            }

            if (empty($data['o_guarantor_fcard'][$key])) {
                return array('success' => false, 'msg' => '请上传担保人正面身份证');
            }

            if (empty($data['o_guarantor_rcard'][$key])) {
                return array('success' => false, 'msg' => '请上传担保人反面身份证');
            }

            if (empty($data['o_guarantor_auth'][$key])) {
                return array('success' => false, 'msg' => '请上传担保人授权书');
            }

            if (empty($data['o_guarantor_sign'][$key])) {
                return array('success' => false, 'msg' => '请上传担保人签名');
            }

            $cardinfo = $this->getSexBirthAffiliationFromIDCard($data['o_guarantor_card'][$key]);
            if(empty($cardinfo))
                $cardinfo = array(
                    'affiliation'  => '',
                    'birth' => $data['o_guarantor_birth'][$key],
                    'sex' => $data['o_guarantor_sex'][$key]
                );

            $cert['guarantor'][] = array(
                'ct_name' => $data['o_guarantor_name'][$key],
                'ct_code' => $data['o_guarantor_card'][$key],
                'ct_mobile' => $data['o_guarantor_mobile'][$key],
                'ct_sex' => $cardinfo['sex'],
                'ct_birth' => $cardinfo['birth'],
                'ct_affiliation' => $cardinfo['affiliation'],
                'ct_idaddress' => $data['o_guarantor_idaddress'][$key],
                'ct_validity_start' => $data['o_guarantor_validity_start'][$key],
                'ct_validity_end' => $data['o_guarantor_validity_end'][$key],
                'ct_issue' => $data['o_guarantor_issue'][$key],
                'ct_attach' => array(
                    'fcard' => $data['o_guarantor_fcard'][$key],
                    'rcard' => $data['o_guarantor_rcard'][$key],
                    'auth' => $data['o_guarantor_auth'][$key],
                    'sign' => $data['o_guarantor_sign'][$key],
                ),
            );
        }
        //身份证重复判断
        if (count($idcard) != count(array_unique($idcard))) {
            return array('success' => false, 'msg' => '身份证号有重复');
        }

        $model = $this->LoadModel('Public');
        $model->beginTransaction();
        try {
            $model->update('order',array('o_sell_time'=>NOW_TIME),array('`o_id` = ?' => $data['oid']));
            foreach ($cert['guarantor'] as $k => $v) {
                $cert_data = array(
                    'ct_oid' => $data['oid'],
                    'ct_key' => 'guarantor',
                    'ct_attach' => serialize($v['ct_attach']),
                    'ct_name' => $v['ct_name'],
                    'ct_code' => $v['ct_code'],
                    'ct_mobile' => $v['ct_mobile'],
                    'ct_sex' => $v['ct_sex'],
                    'ct_birth' => $v['ct_birth'],
                    'ct_affiliation' => $v['ct_affiliation'],
                    'ct_idaddress' => $v['ct_idaddress'],
                    'ct_validity_start' => $v['ct_validity_start'],
                    'ct_validity_end' => $v['ct_validity_end'],
                    'ct_attach' => serialize($v['ct_attach']),
                    'ct_dateline' => NOW_TIME,
                );
                $header = \yii2api\classes\components\auth\Auth::getHeader();
                $body = array(
                    'mobile' => $v['ct_mobile'],
                    'idcard' => $v['ct_code']
                );
                $reponse = \Httpful\Request::post($base_url.$uri)->body($body)->sendsType(\Httpful\Mime::FORM)->addHeaders($header)->send();
                $cert_data['ct_fico_result'] = serialize($this->object2array_pre($reponse->body->data));
                $cert_id = $model->save('order_cert', $cert_data);
                foreach ($v['ct_attach'] as $ik => $iv) {
                    $model->update('attach_image', array('ai_no' => $cert_id), array('`ai_path` = ?' => $iv));
                }
                // 往接口抛送
                $order_id = $data['oid'];
                $order = $model->getOneRow('order', '*', array('`o_id` = ?' => $order_id));
                $credit_data = array(
                    'user_id' => $order_id,
                    'bairong_validate' => 1,
                    'bank_name'=>$order['o_bank'],
                    'orderno' => '!ysjr' . substr((1000000000000 + $order_id), 1, 12),
                    'master_name' => $order['o_vip_name'],
                    'custom_name' => $v['ct_name'],
                    'relation' => '担保人',
                    'idtype' => '000',
                    'idno' => $v['ct_code'],
                    'mobile' => $v['ct_mobile'],
                    'pics' => array(
                        array(
                            'picid' => '0002',
                            'picurl' => StringCode::doUrlimage($v['ct_attach']['fcard']),
                        ),
                        array(
                            'picid' => '0003',
                            'picurl' => StringCode::doUrlimage($v['ct_attach']['rcard']),
                        ),
                        array(
                            'picid' => '0001',
                            'picurl' => StringCode::doUrlimage($v['ct_attach']['auth']),
                        ),
                        array(
                            'picid' => '0004',
                            'picurl' => StringCode::doUrlimage($v['ct_attach']['sign']),
                        ),
                    ),
                );
                //if ($order['o_bank'] == '中国工商银行股份有限公司杭州延中支行' || $order['o_bank'] == '（2017）中国工商银行股份有限公司杭州延中支行'):
                    //$credit_data['bank_sign_code'] = \yii2api\Config::$bank['icbc_bank_sign_code'];
                $x = \yii2api\classes\yii2api\Bank::submitCredit($credit_data);
                if ($x->msg_code == '2001') {
                    //请将上一次的征信结果，直接保存order_cert表
                }
                if ($x->msg_code == '2002') {
                    $model->update('order_cert', array('ct_remark' => '银行灰名单客户', 'ct_results' => '已查询'), array('`ct_id` = ?' => $cert_id));
                }
                $this->updateBigDataforOrdercert($cert_id, $x);
                file_put_contents(YII2API_PHP_SDK_DIR . "/yii2api/logs/api_back_data.log", "\n\n\n" . date("Y-m-d H:i:s") . "\n" . var_export($x, true) . "\n", FILE_APPEND);
                //endif;
            }
            $model->update('order', array('o_status' => '征信提交'), array('`o_id` = ?' => $data['oid']));
            //日志保存
            $log_data = array(
                'log_uid' => $data['uid'],
                'log_action' => 'update',
                'log_related_id' => $data['oid'],
                'log_explain' => '担保人补录',
                'log_dateline' => NOW_TIME,
            );
            $model->save('order_log', $log_data);
            $model->commit();
            return array('success' => true, 'msg' => $data['oid']);
        } catch (Exception $ex) {
            $model->rollBack();
            return array('success' => false, 'msg' => '保存异常');
        }
    }

    public function updateBigDataforOrdercert($certid, $bigdata){
        $model = $this->LoadModel('Public');
        $certData = array(
            'ct_bigdata' => $bigdata->order->big_data_validate_data,
            'ct_bigdata_number' => $bigdata->order->big_data_validate_detail_shift_number,
            'ct_bigdata_org' => '百融金服',
            'ct_bairong_result' => json_encode($bigdata->bairong_result),
        );
        $model->update('order_cert', $certData, array('`ct_id` = ?' => $certid));
    }

    /**
     * 初审审核
     * @param type $data
     * @param type $oid
     */
    public function dataReview($data, $oid)
    {
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order', '*', array('`o_id` = ?' => $oid));
        if (empty($order_row)) {
            return array('success' => false, 'msg' => '订单不存在');
        }

        if (!in_array($order_row['o_status'], array('初审提交', '审核中')) && $order_row['o_trial_status'] != '未审核') {
            return array('success' => false, 'msg' => '当前订单状态不允许初审操作');
        }

        $model->beginTransaction();
        try {
            if ($data['a_uid']) {
                $member_row = $model->getOneRow('member', array('u_realname'), array('`u_id` = ?' => $data['a_uid']));
                $data['a_uname'] = $member_row['u_realname'];
            }
            $data['a_results'] = $data['a_results'] == '可以办理' ? '通过' : '退单';
            if ($data['draft'] == false) {
                if ($data['a_results'] == '通过') {
                    $order_data = array('o_trial_status' => '已通过', 'o_first_atime' => NOW_TIME);
                    if ($order_row['o_pre_mode'] == 1) {
                        $model->save('order_index', array('ot_id' => $data['oid'], 'ot_type' => '层级审核', 'ot_dateline' => NOW_TIME));
                    } else {
                        //预审及超级预审模式 如果层审已经完成 则变成终审通过
                        if ($order_row['o_layer_status'] == '已通过'&& $order_row['o_videoaudit_status'] == '已通过' ) {
                            //$order_data = array('o_status' => '终审通过', 'o_finishe_time' => NOW_TIME, 'o_finishs_time' => NOW_TIME);
                            $order_data['o_status'] = '终审通过';
                            //增加同步任务
                            $model->save('task', array(
                                'task_type' => 'ordersync',
                                'task_releid' => $oid,
                                'task_addtime' => NOW_TIME,
                            ));
                        }
                    }
                    if($order_row['o_layer_status']=='暂停中'){
                        $order_data['o_suspend_status']=1;
                    }elseif($order_row['o_layer_status']=='已通过'){
                        $order_data['o_suspend_status']=0;
                    }
                } else {
                    //$order_data = array('o_trial_status' => '未通过', 'o_status' => '退回', 'o_first_atime' => NOW_TIME, 'o_quit_status' => $order_row['o_status'], 'o_quit_time' => NOW_TIME);
                    $order_data = array('o_trial_status' => '未审核','o_layer_status' => '未审核', 'o_layer_aucode' => '', 'o_status' => '退回', 'o_first_atime' => NOW_TIME, 'o_quit_status' => $order_row['o_status'], 'o_quit_time' => NOW_TIME);
                    $model->update('order_audit', array('a_status' => 'del'), array('`a_oid` = ?' => $oid,'`a_results` = ?' => '暂停'));
                    $order_data['o_suspend_status']=0;

                }
                $order_data['o_first_atime'] = NOW_TIME;
                //$order_data['o_perch'] = 0;
                //$order_data['o_perch_name'] = '';
                $model->update('order', $order_data, array('`o_id` = ?' => $oid));
                //日志保存
                $log_data = array(
                    'log_uid' => $data['a_uid'],
                    'log_action' => 'first_audit',
                    'log_related_id' => $oid,
                    'log_explain' => '资料初审',
                    'log_dateline' => NOW_TIME,
                );
                $model->save('order_log', $log_data);
                $data['a_status'] = 'ok';
            } else {
                $data['a_status'] = 'draft';
            }
            //
            $data['a_type'] = '初审审核';
            $data['a_oid'] = $oid;
            $data['a_dateline'] = date('Y-m-d H:i:s');
            $data['a_info'] = serialize($order_row);
            $model->save('order_audit', $data);
            $model->commit();
            return array('success' => true, 'msg' => '保存成功');
        } catch (Exception $ex) {
            $model->rollBack();
            return array('success' => false, 'msg' => '保存异常');
        }
    }

    /**
     * 资料终审
     * @param type $data
     * @param type $oid
     * @return type
     */
    public function dataFinal($data, $oid)
    {
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order', '*', array('`o_id` = ?' => $oid));
        if (empty($order_row)) {
            return array('success' => false, 'msg' => '订单存在');
        }
        if (!in_array($order_row['o_status'], array('初审提交', '审核中'))) {
            return array('success' => false, 'msg' => '当前订单状态不允许终审操作');
        }
        if (empty($data['a_uid'])) {
            return array('success' => false, 'msg' => '审核人信息错误');
        }
        $member_row = $model->getOneRow('member', array('u_realname', 'u_auditlevel'), array('`u_id` = ?' => $data['a_uid']));
        $audit_row = $model->getOneRow('setting_audit', '*', array('`au_id` = ?' => $member_row['u_auditlevel']));
        if (empty($audit_row)) {
            return array('success' => false, 'msg' => '没有指定的可审核级别金额');
        }
        $branch_msg = $model->getOneRow('branch','*',array('`br_id` = ?' => $order_row['o_branch_id']));
        //获取各审核等级审核员todo:这块数据持久化
        //$auditor_arr = $model->getList('member','*',array('`u_dp_type` =?' => 'dp','`u_auditlevel` >?' => 0,'`u_status` =?' =>'ok'));
        //foreach($auditor_arr as $k => $v){
        //    if($v['u_auditlevel'] == 5){
        //        $onelevel_auditor[] = $v['u_id']; //初级
        //    }elseif($v['u_auditlevel'] == 6){
        //        $twolevel_auditor[] = $v['u_id']; //高级
        //    }elseif($v['u_auditlevel'] == 7){
        //        $threelevel_auditor[] = $v['u_id']; //主管
        //    }elseif($v['u_auditlevel'] == 8){
        //        $fourlevel_auditor[] = $v['u_id']; //经理
        //    }elseif($v['u_auditlevel'] == 9){
        //        $fivelevel_auditor[] = $v['u_id']; //总监
        //    }
        //}
        $model->beginTransaction();
        try {
            $final_flag = false;
            $data['a_uname'] = $member_row['u_realname'];
            $data['a_results'] = $data['a_results'] == '可以办理' ? '通过' : '退单';
            if ($data['draft'] == false) {
                if ($data['a_results'] == '通过') {
                    $final_audit = false;
                    //修改担保人类型
                    if(isset($data['ct_guarantor'])){
                        foreach($data['ct_guarantor'] as $key => $val){
                            $g_type = strstr($val['ct_guarantor_type'],'银行')?'银行共同还款人':'公司担保人';
                            $model->update('order_cert',array('ct_guarantor_type' =>$g_type ),array('`ct_id` =?' => $val['ct_id']));
                        }
                    }
                    if ($order_row['o_pre_mode'] == 1) {
                        //
                        if ($audit_row['au_ceiling'] * 10000 > $order_row['o_loan_money']) {
                            //直接变成终审通过
                            $order_data = array('o_status' => '终审通过', 'o_layer_status' => '已通过', 'o_layer_aucode' => $audit_row['au_code'], 'o_finishe_time' => NOW_TIME, 'o_finishs_time' => NOW_TIME, 'o_web_risk' => $data['o_web_risk'], 'o_rebate_per' => $data['o_rebate_per']);
                            //增加同步任务
                            $model->save('task', array(
                                'task_type' => 'ordersync',
                                'task_releid' => $oid,
                                'task_addtime' => NOW_TIME,
                            ));
                            $final_flag = true;
                        } else {
                            $order_data = array('o_layer_status' => '审核中', 'o_layer_aucode' => $audit_row['au_code'], 'o_web_risk' => $data['o_web_risk'], 'o_rebate_per' => $data['o_rebate_per'],'o_final_perch'=>'');
                        }
                    } else {
                        if ($audit_row['au_ceiling'] * 10000 >= $order_row['o_loan_money']) {
                            $audit_row['au_code'] = 'A00003';
                            $order_data = array('o_layer_status' => '已通过', 'o_layer_aucode' => $audit_row['au_code'], 'o_finishs_time' => NOW_TIME, 'o_web_risk' => $data['o_web_risk'], 'o_rebate_per' => $data['o_rebate_per'], 'o_needgps' => $data['o_needgps']);
                            if($order_row['o_loan_money']>80000){
                                $order_data = array('o_layer_status' => '已通过', 'o_layer_aucode' => $audit_row['au_code'], 'o_finishs_time' => NOW_TIME);
                            }
                            //预审及超级预审模式 如果层审已经完成 则变成终审通过
                            if ($order_row['o_trial_status'] == '已通过' && $order_row['o_videoaudit_status'] == '已通过') {
                                $order_data['o_status'] = '终审通过';
                                $order_data['o_finishe_time'] = NOW_TIME;
                                $order_data['o_finishs_time'] = NOW_TIME;
                                //增加同步任务
                                $model->save('task', array(
                                    'task_type' => 'ordersync',
                                    'task_releid' => $oid,
                                    'task_addtime' => NOW_TIME,
                                ));
                            }
                        } else {
                            $audit_row['au_code'] = 'A00001';
                            $order_data = array('o_layer_status' => '审核中', 'o_layer_aucode' => $audit_row['au_code'], 'o_web_risk' => $data['o_web_risk'], 'o_rebate_per' => $data['o_rebate_per'], 'o_finishe_time' => NOW_TIME,'o_needgps' => $data['o_needgps']);
                            $this->telPerch($oid,'audit');
                            /*if($order_row['o_loan_money']<=150000 &&$order_row['o_loan_money'] > 80000){
                                if(in_array($branch_msg['br_audit_uid'],$threelevel_auditor)){
                                    $order_data['o_final_perch'] = $branch_msg['br_audit_uid'];
                                }else{
                                    $count = count($threelevel_auditor)-1;
                                    $key = rand(0,$count);
                                    $order_data['o_final_perch'] = ($order_row['o_bank_id'] == 12 || $count<0)? 0: $threelevel_auditor[$key];
                                }
                            }elseif($order_row['o_loan_money']<=300000 &&$order_row['o_loan_money'] > 150000){
                                if(in_array($branch_msg['br_audit_uid'],$fourlevel_auditor)){
                                    $order_data['o_final_perch'] = $branch_msg['br_audit_uid'];
                                }else{
                                    $count = count($fourlevel_auditor)-1;
                                    $key = rand(0,$count);
                                    $order_data['o_final_perch'] = ($order_row['o_bank_id'] == 12 || $count<0)? 0: $fourlevel_auditor[$key];
                                }
                            }elseif($order_row['o_loan_money'] > 300000){
                                if(in_array($branch_msg['br_audit_uid'],$fivelevel_auditor)){
                                    $order_data['o_final_perch'] = $branch_msg['br_audit_uid'];
                                }else{
                                    $count = count($fivelevel_auditor)-1;
                                    $key = rand(0,$count);
                                    $order_data['o_final_perch'] = ($order_row['o_bank_id'] == 12 || $count<0)? 0: $fivelevel_auditor[$key];
                                }
                            }
                            $final_msg = $model->getRow('order_audit', '*', array('`a_oid` = ?' => $data['oid'], '`a_type` = ?' => 'A00003终审审核','`a_status` =?' =>'ok'), null, array('a_id DESC'));
                            if(!empty($final_msg)){
                                $order_data['o_final_perch'] = $final_msg['a_uid'];
                            }*/
                        }
                    }
                    if($order_row['o_trial_status']=='暂停中'){
                        $order_data['o_suspend_status']=1;
                    }elseif($order_row['o_trial_status']=='已通过'){
                        $order_data['o_suspend_status']=0;
                    }
                } else {
                    //$order_data = array('o_status' => '退回', 'o_layer_status' => '未通过', 'o_layer_aucode' => $audit_row['au_code'], 'o_finishs_time' => NOW_TIME, 'o_quit_status' => $order_row['o_status'], 'o_web_risk' => $data['o_web_risk'], 'o_rebate_per' => $data['o_rebate_per'], 'o_quit_time' => NOW_TIME);
                    $order_data = array('o_status' => '退回', 'o_trial_status' => '未审核','o_layer_status' => '未审核', 'o_layer_aucode' => '', 'o_finishs_time' => NOW_TIME, 'o_quit_status' => $order_row['o_status'], 'o_web_risk' => $data['o_web_risk'], 'o_rebate_per' => $data['o_rebate_per'], 'o_quit_time' => NOW_TIME);
                    $model->update('order_audit', array('a_status' => 'del'), array('`a_oid` = ?' => $oid,'`a_results` = ?' => '暂停'));
                    $order_data['o_suspend_status']=0;
                }
                //$order_data['o_perch'] = 0;
                //$order_data['o_perch_name'] = '';
                $order_data['o_finishe_time'] = NOW_TIME;
                $order_data['o_last_perch'] = $data['a_uid'];
                //$order_data['o_final_perch'] = 0;
                $model->update('order', $order_data, array('`o_id` = ?' => $oid));

                //日志保存
                $log_data = array(
                    'log_uid' => $data['a_uid'],
                    'log_action' => 'final_audit',
                    'log_related_id' => $oid,
                    'log_explain' => $audit_row['au_code'] . '终审审核',
                    'log_dateline' => NOW_TIME,
                );
                $model->save('order_log', $log_data);
                $data['a_status'] = 'ok';
            } else {
                $audit_row['au_code'] = $audit_row['au_ceiling'] * 10000 >= $order_row['o_loan_money']? 'A00003': 'A00001';
                $data['a_status'] = 'draft';
            }
            //
            $data['a_type'] = $audit_row['au_code'] . '终审审核';
            $data['a_dateline'] = date('Y-m-d H:i:s');
            $data['a_oid'] = $oid;
            $data['a_info'] = serialize($order_row);
            $model->save('order_audit', $data);
            $model->commit();
            return array('success' => true, 'msg' => '保存成功', 'data' => array('draft' => $data['draft'], 'flag' => $final_flag));
        } catch (Exception $ex) {
            $model->rollBack();
            return array('success' => false, 'msg' => '保存异常');
        }
    }

    /**
     * 资料复核
     * @param type $data
     * @param type $oid
     * @return type
     */
    public function dataRecheck($data, $oid)
    {
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order', '*', array('`o_id` = ?' => $oid));
        if (empty($order_row)) {
            return array('success' => false, 'msg' => '订单不存在');
        }

        if ($order_row['o_review_status'] == '已通过' && $data['savetype'] == 'save') {
            return array('success' => false, 'msg' => '当前订单已复核通过不允许复核操作');
        }

        $model->beginTransaction();
        try {
            $final_flag = false;
            if ($data['a_uid']) {
                $member_row = $model->getOneRow('member', array('u_realname'), array('`u_id` = ?' => $data['a_uid']));
                $data['a_uname'] = $member_row['u_realname'];
            }
            //$data['a_results'] = $data['a_results'] == '可以办理' ? '通过' : '退单';
            $data['a_oid'] = $oid;
            if ($data['draft'] == false) {
                //if ($data['a_results'] == '通过') {
                    $order_data = array('o_review_status' => '已通过');
                    //增加同步任务
                    //                    $model->save('task', array(
                    //                        'task_type' => 'ordersync',
                    //                        'task_releid' => $oid,
                    //                        'task_addtime' => NOW_TIME
                    //                    ));
                    $final_flag = true;
               // }
                //else {
                //    $order_data = array('o_status' => '退回111111', 'o_quit_status' => $order_row['o_status'], 'o_quit_time' => NOW_TIME);
                //}
                $model->update('order', $order_data, array('`o_id` = ?' => $oid));

                //日志保存
                $log_data = array(
                    'log_uid' => $data['a_uid'],
                    'log_action' => 'final_review',
                    'log_related_id' => $oid,
                    'log_explain' => '复核审核',
                    'log_dateline' => NOW_TIME,
                );
                $model->save('order_log', $log_data);
                $data['a_status'] = 'ok';
            } else {
                $model->update('order', array('o_review_status' =>'未通过'), array('`o_id` = ?' => $oid));
                $data['a_status'] = 'draft';
            }
            //
            $data['a_type'] = '复核审核';
            $data['a_results'] = '通过';
            $data['a_dateline'] = date('Y-m-d H:i:s');
            $data['a_oid'] = $oid;
            $data['a_info'] = serialize($order_row);
            $check_audit = $model->getOneRow('order_audit','*',array('`a_oid` =?' =>$oid,'`a_type` =?' =>'复核审核'));
            if(empty($check_audit)){
                $model->save('order_audit', $data);
            }else{
                $model->update('order_audit',$data,array('`a_oid` =?' =>$oid,'`a_type` =?' =>'复核审核'));
            }
            $model->commit();
            return array('success' => true, 'msg' => '保存成功', 'data' => array('draft' => $data['draft'], 'flag' => $final_flag));
        } catch (Exception $ex) {
            $model->rollBack();
            return array('success' => false, 'msg' => '保存异常');
        }
    }

    /**
     * 签出
     * @param type $oid
     * @param type $level
     * @return type
     */
    public function orderChkout($oid, $level = '资料审核', $member = array())
    {
        /*
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order', '*', array('`o_id` = ?' => $oid));
        if(empty($order_row)) return array('success' => false, 'msg' => '订单存在');
        switch($order_row['o_status']){
        case '初审提交':
        $a_type = '初审签出';
        break;
        case '初审通过':
        $a_type = '终审签出';
        break;
        case '终审提交':
        $a_type = '复核签出';
        break;
        }
        $level_check = $model->getOneRow('setting_audit', '*', array('`au_status` = ?' => 'ok', '`au_level` = ?' => $level));
        if (empty($level_check)) {
        return array('success' => false, 'msg' => '没有当前审核级别的签出设置');
        } else {
        $order_car = $model->getOneRow('order_car', array('ot_loan_limit'), array('`ot_oid` = ?' => $oid, '`ot_status` = ?' => 'ok'));
        if (empty($order_car)) {
        return array('success' => false, 'msg' => '未找到当前订单的贷款额度');
        }
        if ($order_car['ot_loan_limit'] > $level_check['au_ceiling'] * 10000) {
        return array('success' => false, 'msg' => '贷款额度超过可迁出额度');
        }
        //更新订单至终审状态
        $model->update('order', array('o_status' => '终审通过', 'o_finishe_time' => NOW_TIME), array('`o_id` = ?' => $oid));
        //日志保存
        $log_data = array(
        'log_uid' => $member['uid'],
        'log_action' => 'checkout',
        'log_related_id' => $oid,
        'log_explain' => $level . '签出',
        'log_dateline' => NOW_TIME
        );
        $model->save('order_log', $log_data);
        $model->save('order_audit', array(
        'a_oid' => $oid,
        'a_type' => $a_type,
        'a_uid' => $member['uid'],
        'a_uname' => $member['uname'],
        'a_dateline' => date('Y-m-d'),
        'a_status' => 'ok'
        ));
        return array('success' => false, 'msg' => '签出成功');
        }
        return array('success' => false, 'msg' => '签出失败');
         *
         */
        //20170319签出改为取消占位
        $model = $this->LoadModel('Public');
        if ($level == '终审') {
            $data = array('o_final_perch' => 0);
        } elseif($level == '视频审'){
            $data = array('o_videoaudit_perch' => 0 );
        }else {
            $data = array('o_perch' => 0, 'o_perch_name' => '');
        }
        $do = $model->update('order', $data, array('`o_id` = ?' => $oid));
        return array('success' => true, 'msg' => '取消占位成功');
    }

    /**
     * 订单退回
     * @param type $oid
     * @return type
     */
    public function orderBack($oid, $status, $remarks = '', $member = array(), $v_type='',$lock='')
    {
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order', '*', array('`o_id` = ?' => $oid));
        if (empty($order_row)) {
            return array('success' => false, 'msg' => '订单不存在');
        }
        $oldinfo_row = $model->getOneRow('order_oldinfo','*',array('`o_app_id` =?' => $oid));
        if($oldinfo_row['o_adtime'] > 0){
            return array('success' => false, 'msg' => '该订单公司已垫款,无法退回');
        }
        if($oldinfo_row['o_bank_time'] > 0){
            return array('success' => false, 'msg' => '该订单银行已放款,无法退回');
        }
        if($oldinfo_row['o_pact_totime'] > 0){
            return array('success' => false ,'msg' => '该订单已送交银行,无法退回');
        }

        /*
        switch($order_row['o_status']){
        case '初审提交':
        $a_type = '初审退回';
        break;
        case '初审通过':
        $a_type = '终审退回';
        break;
        case '终审提交':
        $a_type = '复核退回';
        break;
        }
         *
         */
        $a_type = '订单退回';
        if ($v_type == 'ftooprate'){
            $a_type = '初审审核';
        }elseif($v_type == 'faooprate'){
            $a_type = '终审审核';
        }elseif($v_type == 'fvooprate'){
            $a_type = '视频审核';
        }elseif($v_type == 'troback'){
            $a_type = '征信过期退回';
        }else{
            $a_type = '复核审核';
        }

        $model->beginTransaction();
        try {
            $up_data = array(
                'o_status' => $status,
                'o_quit_status' => $order_row['o_status'],
                'o_trial_status' => '未审核',
                'o_layer_status' => '未审核',
                'o_review_status' => '未复核',
                'o_videoaudit_status' => '未审核',
                //'o_perch' => 0,
                //'o_perch_name' => '',
                'o_final_perch' => 0,
                'o_videoaudit_time' => 0,
                'o_first_time' => 0,
                'o_first_atime' => 0,
                'o_finishs_time' => 0,
                'o_finishe_time' => 0,
                'o_layer_aucode' => '',
                'o_suspend_status' => 0
            );
            if($status =='征信提交'){
                $up_data['o_sell_time'] = NOW_TIME;
                $up_data['o_search_time'] = 0;
                $model->update('order_cert',array('ct_remark' =>'','ct_results' =>'未查询','ct_querytime' => 0),array('`ct_oid` =?' => $oid));
            }
            $model->update('order', $up_data, array('`o_id` = ?' => $oid));
            $model->update('order_car',array('ot_car_lock' => $lock),array('`ot_oid` =?' =>$oid));
            if($order_row['o_bank_id'] ==13){
                $model->update('order_attachment',array('oa_video' => serialize('')),array('`oa_oid` =?' => $oid));//延中退回清除视频信息
            }
            //日志保存
            $log_data = array(
                'log_uid' => $member['uid'],
                'log_action' => 'orderback',
                'log_related_id' => $oid,
                'log_explain' => '退回',
                'log_dateline' => NOW_TIME,
            );
            $model->save('order_log', $log_data);
            $model->update('order_audit', array('a_status' => 'del'), array('`a_oid` = ?' => $oid,'`a_results` = ?' => '暂停'));
            $model->save('order_audit', array(
                'a_oid' => $oid,
                'a_type' => $a_type,
                'a_results' => '退回',
                'a_uid' => $member['uid'],
                'a_uname' => $member['uname'],
                'a_dateline' => date('Y-m-d H:i:s'),
                'a_status' => 'ok',
                'a_remarks' => $remarks,
                'a_details' => '订单退回至：' . $status,
                'a_info' => serialize($order_row),
            ));
            //删除原物流信息);
            $logistics_row = $model->getRow('logistics', '*', array('`ls_oid` = ?' => $oid, '`ls_status` != ?' => 'del'), null, array('ls_id DESC'));
            $model->update('order_up',array('up_status' => '作废'),array('`up_oid` =?'=>$oid,'`up_status` =?' =>'申请中'));
            $model->update('logistics', array('ls_status' => 'del'), array('`ls_oid` = ?' => $oid, '`ls_id` != ?' => empty($logistics_row) ? 0 : $logistics_row['ls_id']));
            //退回到征信查询同步
            if($status =='征信查询'){
                $task_data = array(
                    'task_type' => 'ordersync',
                    'task_releid' => $oid,
                    'task_addtime' => NOW_TIME
                );
                $model->save('task',$task_data);
            }
            $model->commit();
            return array('success' => true, 'msg' => '退单成功');
        } catch (Exception $ex) {
            $model->rollBack();
            return array('success' => false, 'msg' => '出现异常' . $ex->getMessage());
        }
    }

    /**
     * 审核暂停
     * @param type $oid
     * @return type
     */
    public function orderSuspend($oid, $remarks = '', $member = array(),$type)
    {
        $model = $this->LoadModel('Public');
        $order_msg = $model->getOneRow('order', '*', array('`o_id` = ?' => $oid));
        if (empty($order_msg)) {
            return array('success' => false, 'msg' => '订单不存在');
        }
        $model->beginTransaction();
        try {
            if($type =='fao'){
                $a_type = '终审审核';
                $new_order_data = array('o_layer_status' => '暂停中');
                $order_msg['o_layer_status'] = '暂停中';
            }elseif($type =='fto'){
                $a_type = '初审审核';
                $new_order_data = array('o_trial_status' => '暂停中');
                $order_msg['o_trial_status'] = '暂停中';
            }elseif($type == 'fvo'){
                $a_type = 'A00002终审审核';
                $new_order_data = array('o_videoaudit_status' => '暂停中');
                $order_msg['o_videoaudit_status'] = '暂停中';
            }
            $status=array('暂停中','已通过');
            if(in_array($order_msg['o_trial_status'],$status) && in_array($order_msg['o_layer_status'],$status) && in_array($order_msg['o_videoaudit_status'],$status)){
                $new_order_data['o_suspend_status']=1;
            }
            $model->update('order', $new_order_data, array('`o_id` = ?' => $oid));
            $order_audit_data = array(
                'a_oid' => $oid,
                'a_type' => $a_type,
                'a_results' =>'暂停',
                'a_details'=> '',
                'a_remarks' => $remarks,
                'a_uid' => $member['uid'],
                'a_uname' => $member['uname'],
                'a_dateline' => date('Y-m-d H:i:s'),
                'a_status' => 'ok',
                'a_info' => serialize($order_msg)
                );
            $model->save('order_audit',$order_audit_data);
            $model->commit();
            return array('success' => true, 'msg' => '暂停成功');
    }catch (Exception $ex) {
            $model->rollBack();
            return array('success' => false, 'msg' => '出现异常' . $ex->getMessage());
    }
}

    /**
     * 订单列表
     * @param type $where
     * @param type $page
     * @param type $limit
     * @param type $param
     * @param type $member
     * @return type
     */
    public function orderList($where, $page = 1, $limit = PAGE_SIZE, $param = array(), $member = array(), $table = 'order', $order_by = array('o_id DESC'))
    {
        $model = $this->LoadModel('Public');
        if (!empty($member)) {
            switch ($member['u_scope']) {
                case '用户级':
//                    if (!empty($member['u_bank'])) {
                    //                        $where['`o_bank_id` IN (?)'] = explode(',', $member['u_bank']);
                    //                    } else {
                    //                        $where['`o_bank_id` IN (?)'] = array(0);
                    //                    }
                    if ($member['u_dp_type'] == 'rg') {
                        $dot_id = array(0);
                        $branch = $model->getList('branch', array('br_id'), array('`br_uid` = ?' => $member['u_id'], '`br_status` = ?' => 'ok'));
                        if (!empty($branch)) {
                            foreach ($branch as $k => $v) {
                                $dot_id[] = $v['br_id'];
                            }
                        }
                        $where['`o_branch_type` = "dot" AND o_branch_id IN (?)'] = $dot_id;
                    } else {
                        $where['`o_uid` = ?'] = $member['u_id'];
                        $where['`o_branch_id` = ?'] = $member['u_dp_id'];
                    }
                    break;
                case '部门级':
                    switch ($member['u_dp_type']) {
                        case 'dp': //部门，自己部门的订单
                            $where['`o_branch_type` = ?'] = 'dp';
                            $where['`o_branch_id` = ?'] = $member['u_dp_id'];
                            break;
                        case 'dot': //网点 自己网点的订单
                            $where['`o_branch_type` = ?'] = 'dot';
                            $where['`o_branch_id` = ?'] = $member['u_dp_id'];
                            break;
                        case 'rg': //大区 大区下所有网点订单
                            $dot_id = array(0);
                            $branch = $model->getList('branch', array('br_id'), array('`br_rgid` = ?' => $member['u_dp_id'], '`br_status` = ?' => 'ok'));
                            if (!empty($branch)) {
                                foreach ($branch as $k => $v) {
                                    $dot_id[] = $v['br_id'];
                                }
                            }

                            $where['(`o_branch_type` = "rg" AND `o_branch_id` = ' . $member['u_dp_id'] . ') OR (`o_branch_type` = "dot" AND o_branch_id IN (?))'] = $dot_id;
                            break;
                    }
                    if (in_array($member['u_dp_type'], array('dp'))) {
                        if (!empty($member['u_bank'])) {
                            $where['`o_bank_id` IN (?)'] = explode(',', $member['u_bank']);
                        } else {
                            $where['`o_bank_id` IN (?)'] = array(0);
                        }
                    }
                    break;
                case '单位级':
                    if (!empty($member['u_bank'])) {
                        $where['`o_bank_id` IN (?)'] = explode(',', $member['u_bank']);
                    }
                    break;
                default:
                    $where['`o_uid` = ?'] = $member['u_id'];
            }
        }
        $where = array_merge($where, $this->orderCondition($param));
        $data['count'] = $model->getRowCount($table, $where);
        $data['where'] = $where;
        if (!empty($data['count'])) {
            $data['all'] = $model->getList($table, '*', $where, array($page, $limit), null, $order_by);
            Pagination::SetUrl($Param);
            $data['page'] = Pagination::GetHtml($limit, $page, $data['count']);
            $data['pagetotal'] = ceil($data['count'] / $limit);
        }
        return $data;
    }

    public function orderCarList($where,$text)
    {
        $model = $this->LoadModel('Public');
        $data= $model->getList('order_car',$text,$where);
        return $data;
    }

    /**
     * 查询条件合成
     * @param type $param
     * @return type
     */
    public function orderCondition($param)
    {
        $where = array();
        foreach($param as $k =>$v){
            $param[$k] = trim($v); 
        }
//        if (!empty($param['o_vip_name'])) {
        //            $where['LOCATE (?,`o_vip_name`)  > 0'] = $param['o_vip_name'];
        //        }
        if (!empty($param['o_add_time_st'])) {
            $where['`o_add_time` >= ?'] = $param['o_add_time_st'];
        }
        if (!empty($param['o_add_time_et'])) {
            $where['`o_add_time` < ?'] = $param['o_add_time_et'];
        }
        if (!empty($param['o_bank_id'])) {
            $where['`o_bank_id` = ?'] = $param['o_bank_id'];
        }
        if (!empty($param['o_business_uid'])) {
            $where['`o_business_uid` = ?'] = $param['o_business_uid'];
        }
        if (!empty($param['o_branch'])) {
            $where['LOCATE (?,`o_branch`)  > 0'] = $param['o_branch'];
        }
        if (!empty($param['o_bank'])) {
            $where['LOCATE (?,`o_bank`)  > 0'] = $param['o_bank'];
        }
        if (!empty($param['o_number'])) {
            $where['LOCATE (?,`o_number`)  > 0'] = $param['o_number'];
        }
        if (!empty($param['o_keyword']) || !empty($param['key'])) {
//            $model = $this->LoadModel('Public');
            //            if (Validator::isMobile($param['key'])) {
            //                $o_id = array(0);
            //                $owner = $model->getOneRow('order_owner', array('ot_id'), array('`ot_status` = ?' => 'ok', '`ot_mobile` = ?' => $param['key']));
            //                if (!empty($owner))
            //                    foreach ($owner as $k => $v) {
            //                        $o_id[] = $v['ot_id'];
            //                    }
            //                $where['`o_id` IN (?)'] = $o_id;
            //            } elseif (Validator::isIdcard($param['key'])) {
            //                $where['`o_vip_card` = ?'] = $param['key'];
            //            } else {
            //                $where['`o_vip_name` = ?'] = $param['key'];
            //            }
            //后期改善
            $param['key'] = !empty($param['o_keyword']) ? $param['o_keyword'] : $param['key'];
            $db_config = Config::GetDb();
            //$where['o_id IN(SELECT ct_oid FROM `' . $db_config['master']['prcode'] . 'order_cert` WHERE LOCATE (?,`ct_detail`)  > 0  GROUP BY ct_oid)'] = $param['key'];
            //$where['o_id IN(SELECT ct_oid FROM `' . $db_config['master']['prcode'] . 'order_cert` WHERE (LOCATE (?,`ct_name`)  > 0 OR LOCATE (?, `ct_code`) > 0 )  GROUP BY ct_oid)'] = $param['key'];
            $where['o_id IN(SELECT o_id FROM `' . $db_config['master']['prcode'] . 'order` WHERE (LOCATE (?,`o_vip_name`)  > 0 OR LOCATE (?, `o_number`) > 0 )  UNION SELECT ct_oid FROM `' . $db_config['master']['prcode'] . 'order_cert` WHERE (LOCATE (?,`ct_name`)  > 0 OR LOCATE (?, `ct_code`) > 0 OR LOCATE (?,`ct_mobile`)  > 0) )'] = $param['key'];
                
        }
        return $where;
    }

    /**
     * 订单信息
     * @param type $where
     * @return type
     */
    public function orderRow($where)
    {
        if (is_numeric($where)) {
            $where = array('`o_id` = ?' => $where);
        }
        $model = $this->LoadModel('Public');
        $data = $model->getOneRow('order', '*', $where);
        return $data;
    }

    /**
     * 征信保存
     * @param type $data
     * @param type $where
     * @return type
     */
    public function certSave($data, $where = '')
    {
        if (is_numeric($where)) {
            $where = array('`ct_id` = ?' => $where);
        }
        $model = $this->LoadModel('Public');
        if (empty($where)) {
            $id = $model->save('order_cert', $data);
            if ($id) {
                return array('success' => true, 'msg' => $id);
            } else {
                return array('success' => false, 'msg' => '保存失败');
            }
        } else {
            $model->update('order_cert', $data, $where);
            return array('success' => true);
        }
    }

    /**
     * 根据征信查询ID获取所有信息
     * @param type $ct_id
     */
    public function certOrder($ct_id)
    {
        $cert_info = $this->certRow(array('`ct_id` = ?' => $ct_id, '`ct_status` = ?' => 'ok'));
        if (empty($cert_info)) {
            return false;
        }

        $model = $this->LoadModel('Public');
        $order = $this->orderRow($cert_info['ct_oid']);
        $cert_info['order'] = $order;
        return $cert_info;
    }

    /**
     * 征信数据
     * @param type $where
     * @return type
     */
    public function certRow($where)
    {
        if (is_numeric($where)) {
            $where = array('`ct_id` = ?' => $where);
        }
        $model = $this->LoadModel('Public');
        $data = $model->getOneRow('order_cert', $this->cert_fields, $where);
        if (!empty($data)) {
            $data['ct_attach'] = unserialize($data['ct_attach']);
        }

        return $data;
    }

    /**
     * 征信数据
     * @param type $where
     * @return type
     */
    public function certList($where)
    {
        if (is_numeric($where)) {
            $where = array('`ct_id` = ?' => $where);
        }
        $model = $this->LoadModel('Public');
        $data = $model->getList('order_cert', $this->cert_fields, $where);
        if (!empty($data)) {
            for($i=0;$i<count($data);$i++){
                $data[$i]['ct_attach'] = unserialize($data[$i]['ct_attach']);
            }
        }

        return $data;
    }
    public function certAll($where)
    {
        if (is_numeric($where)) {
            $where = array('`ct_oid` = ?' => $where);
        }
        $model = $this->LoadModel('Public');
        $data = $model->getList('order_cert', $this->cert_fields, $where);
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                switch ($v['ct_key']) {
                    case 'vip':
                        $data[$k]['ct_key_text'] = '客户';
                        break;
                    case 'spouse':
                        $data[$k]['ct_key_text'] = '配偶';
                        break;
                    case 'guarantor':
                        $data[$k]['ct_key_text'] = '担保人';
                        break;
                }
            }
        }

        return $data;
    }

    /**
     * 整单单据详情
     * @param type $oid
     * @return type
     */
    public function orderInfo($oid, $showAll = false)
    {
        $model = $this->LoadModel('Public');
        $order = $this->orderRow($oid);
        $order['o_pre_modetext'] = $this->loan_mode[$order['o_pre_mode']]['mode_text'];
        $business_row = $model->getOneRow('member', array('u_realname'), array('`u_id` = ?' => $order['o_business_uid']));
        $order['o_business_uname'] = $business_row['u_realname'];
        $order['owner'] = $model->getOneRow('order_owner', '*', $showAll ? array('`ot_oid` = ?' => $oid) : array('`ot_oid` = ?' => $oid, '`ot_status` != ?' => 'del'));
        $liveadd_arr = explode(" ",$order['owner']['ot_liveadd']);
        $order['owner']['ot_liveadd-province'] = $liveadd_arr[0];
        $order['owner']['ot_liveadd-city'] = $liveadd_arr[1];
        $order['owner']['ot_liveadd-county'] = $liveadd_arr[2];
        $order['owner']['ot_liveadd_address'] = $liveadd_arr[3];
        $homeadd_arr = explode(" ",$order['owner']['ot_home_add']);
        $order['owner']['ot_homeadd-province'] = $homeadd_arr[0];
        $order['owner']['ot_homeadd-city'] = $homeadd_arr[1];
        $order['owner']['ot_homeadd-county'] = $homeadd_arr[2];
        $order['owner']['ot_homeadd_address'] = $homeadd_arr[3];
        $companyadd_arr = explode(" ",$order['owner']['ot_company_add']);
        $order['owner']['ot_companyadd-province'] = $companyadd_arr[0];
        $order['owner']['ot_companyadd-city'] = $companyadd_arr[1];
        $order['owner']['ot_companyadd-county'] = $companyadd_arr[2];
        $order['owner']['ot_companyadd_address'] = $companyadd_arr[3];
        $order['owner']['ot_contact'] = unserialize($order['owner']['ot_contact']);
        $order['buyer'] = $model->getOneRow('order_cert', $this->cert_fields, $showAll ? array('`ct_oid` = ?' => $oid, '`ct_key` = ?' => 'vip') : array('`ct_oid` = ?' => $oid, '`ct_status` = ?' => 'ok', '`ct_key` = ?' => 'vip'));
        /*if(!empty($order['buyer']['ct_bairong_result'])){
            $vip_result = json_decode($order['buyer']['ct_bairong_result']);
            $order['buyer']['ct_bigdata'] = $this->unicodeDecode($vip_result->optimize_show);
            $order['buyer']['ct_bigdata_detail'] = $vip_result->url->detail_list;
            $order['buyer']['ct_bigdata_org'] = '百融金服';
        }*/
        $order['owner']['list_name'] = $order['buyer']['ct_name'];
        $order['owner']['list_sex'] = $order['buyer']['ct_sex'];
        $order['owner']['list_age'] = StringCode::getAge($order['buyer']['ct_birth']);
        $order['owner']['list_idcard'] = $order['buyer']['ct_code'];
        $order['buyer']['list_age'] = $order['owner']['list_age'];
        $order['buyer']['ct_affiliation'] = $this->getCardrt($order['buyer']['ct_code'], 'text');
        $order['buyer']['ct_affiliation_arr'] = empty($order['buyer']['ct_affiliation']) ? array() : explode(" ", $order['buyer']['ct_affiliation']);
        $order['spouse'] = $model->getOneRow('order_cert', $this->cert_fields, $showAll ? array('`ct_oid` = ?' => $oid, '`ct_key` = ?' => 'spouse') : array('`ct_oid` = ?' => $oid, '`ct_status` = ?' => 'ok', '`ct_key` = ?' => 'spouse'));
        /*if(!empty($order['spouse']['ct_bairong_result'])){
                $spouse_result = json_decode($order['spouse']['ct_bairong_result']);
                $order['spouse']['ct_bigdata'] = $this->unicodeDecode($spouse_result->optimize_show);
                $order['spouse']['ct_bigdata_detail'] = $spouse_result->url->detail_list;
                $order['spouse']['ct_bigdata_org'] = '百融金服';
            }*/
        $order['guarantor'] = $model->getList('order_cert', $this->cert_fields, $showAll ? array('`ct_oid` = ?' => $oid, '`ct_key` = ?' => 'guarantor'): array('`ct_oid` = ?' => $oid, '`ct_status` = ?' => 'ok','`ct_key` = ?' => 'guarantor'));
        if ($showAll && $order['o_status'] == '作废') {
            $order['guarantor'] = $model->getList('order_cert', $this->cert_fields, array('`ct_oid` = ?' => $oid, '`ct_key` = ?' => 'guarantor'));
        }
        /*
        foreach($order['guarantor'] as $k=>$v){
            if(!empty($v['ct_bairong_result'])){
                    $msg = json_decode($v['ct_bairong_result']);
                    $order['guarantor'][$k]['ct_bigdata'] = $this->unicodeDecode($msg->optimize_show);
                    $order['guarantor'][$k]['ct_bigdata_detail'] = $msg->url->detail_list;
                    $order['guarantor'][$k]['ct_bigdata_org'] = '百融金服';
                }
        }*/
        $order['car'] = $model->getOneRow('order_car', '*', $showAll ? array('`ot_oid` = ?' => $oid) : array('`ot_oid` = ?' => $oid, '`ot_status` != ?' => 'del'));
        $order['car']['ot_calculated'] = unserialize($order['car']['ot_calculated']);
        $order['car']['ot_service_rate'] = $order['car']['ot_loan_rate'] - $order['car']['ot_bankrt_rate'];
        $order['attachment'] = $model->getOneRow('order_attachment', '*', $showAll ? array('`oa_oid` = ?' => $oid) : array('`oa_oid` = ?' => $oid, '`oa_status` != ?' => 'del'));
        if (!empty($order['spouse'])) {
            $order['spouse']['ct_detail'] = unserialize($order['spouse']['ct_detail']);
            $order['spouse']['list_age'] = StringCode::getAge($order['spouse']['ct_birth']);
            $order['spouse']['ct_affiliation'] = $this->getCardrt($order['spouse']['ct_code'], 'text');
            $order['spouse']['ct_affiliation_arr'] = empty($order['spouse']['ct_affiliation']) ? array() : explode(" ", $order['spouse']['ct_affiliation']);
            if (!empty($order['spouse']['ct_attach'])) {
                $order['spouse']['ct_attach'] = unserialize($order['spouse']['ct_attach']);
                $order['spouse']['ct_attach_url'] = StringCode::doUrlimage($order['spouse']['ct_attach']);
                $order['spouse']['ct_attach_thurl'] = $this->dothurl($order['spouse']['ct_attach']);
            }else{
                $order['spouse']['ct_attach'] = $order['spouse']['ct_attach_url'] = \wodrow\tools\Obj::getAttach();
            }
            if  (!empty($order['spouse']['ct_sign'])){
                $order['spouse']['ct_sign'] = unserialize($order['spouse']['ct_sign']);
                $order['spouse']['ct_sign_url'] = StringCode::doUrlimage($order['spouse']['ct_sign']);
            }else{
                $order['spouse']['ct_sign'] = $order['spouse']['ct_sign_url'] = array();
            }
            if  (!empty($order['spouse']['ct_video'])){
                $order['spouse']['ct_video'] = unserialize($order['spouse']['ct_video']);
                $order['spouse']['ct_video_url'] = StringCode::doUrlimage($order['spouse']['ct_video']);
            }else{
                $order['spouse']['ct_video'] = $order['spouse']['ct_video_url'] = array();
            }
        }
        $order['o_add_time'] = date('Y-m-d H:i:s', $order['o_add_time']);
        $order['o_sell_time'] = date('Y-m-d H:i:s', $order['o_sell_time']);
        $order['o_status_num'] = $this->statusChange($order['status']);
        if (!empty($order['buyer']['ct_attach'])) {
            $order['buyer']['ct_attach'] = unserialize($order['buyer']['ct_attach']);
            $order['buyer']['ct_attach_url'] = StringCode::doUrlimage($order['buyer']['ct_attach']);
            $order['buyer']['ct_attach_thurl'] = $this->dothurl($order['buyer']['ct_attach']);
        }else{
            $order['buyer']['ct_attach'] = $order['buyer']['ct_attach_url'] = \wodrow\tools\Obj::getAttach();
        }
        if  (!empty($order['buyer']['ct_sign'])){
            $order['buyer']['ct_sign'] = unserialize($order['buyer']['ct_sign']);
            $order['buyer']['ct_sign_url'] = StringCode::doUrlimage($order['buyer']['ct_sign']);
        }else{
            $order['buyer']['ct_sign'] = $order['buyer']['ct_sign_url'] = array();
        }
        if  (!empty($order['buyer']['ct_video'])){
            $order['buyer']['ct_video'] = unserialize($order['buyer']['ct_video']);
            $order['buyer']['ct_video_url'] = StringCode::doUrlimage($order['buyer']['ct_video']);
        }else{
            $order['buyer']['ct_video'] = $order['buyer']['ct_video_url'] = array();
        }
        if (!empty($order['guarantor'])) {
            foreach ($order['guarantor'] as $k => $v) {
                $v['ct_attach'] = unserialize($v['ct_attach']);
                $v['ct_sign'] = unserialize($v['ct_sign']);
                $v['ct_video'] = unserialize($v['ct_video']);
//                $order['guarantor'][$k]['ct_attach'] = $v['ct_attach'];
                $order['guarantor'][$k]['ct_attach_url'] = $v['ct_attach']?StringCode::doUrlimage($v['ct_attach']):\wodrow\tools\Obj::getAttach();
                $order['guarantor'][$k]['ct_attach_thurl'] = $this->dothurl($v['ct_attach']);
//                $order['guarantor'][$k]['ct_sign'] = $v['ct_sign']?$v['ct_sign']:array();
                $order['guarantor'][$k]['ct_sign_url'] = $v['ct_sign']?StringCode::doUrlimage($v['ct_sign']):\wodrow\tools\Obj::getAttach();
//                $order['guarantor'][$k]['ct_video'] = $v['ct_vid']?$v['ct_video']:array();
                $order['guarantor'][$k]['ct_video_url'] = $v['ct_video']?StringCode::doUrlimage($v['ct_video']):\wodrow\tools\Obj::getAttach();
                $order['guarantor'][$k]['ct_detail'] = unserialize($v['ct_detail']);
                $order['guarantor'][$k]['list_age'] = StringCode::getAge($v['ct_birth']);
                $order['guarantor'][$k]['ct_affiliation'] = $this->getCardrt($v['ct_code'], 'text');
                $order['guarantor'][$k]['ct_affiliation_arr'] = empty($v['ct_affiliation']) ? array() : explode(" ", $v['ct_affiliation']);
            }
        }
        $order['attachment'] = $this->attachmentOut($order['attachment'], $order['o_pre_mode']);
        $estimae_msg = $model->getOneRow('estimate','*',array('`et_o_number` = ?' => $oid));
        if($estimae_msg){
            $order['car']['et_attach'] = $this->etattachmentOut($estimae_msg['et_attach']);
        }
        if(!empty($order['car']['ot_carcard_img'])){
            $mode=array('car_image');
            $order['car']['attachment'] = $this->etattachmentOut($order['car']['ot_carcard_img'],$mode);
        }
        if(!empty($order['car']['ot_getcar_img'])){
            $mode=array('getcar_image');
            $order['car']['getcar_img'] = $this->etattachmentOut($order['car']['ot_getcar_img'],$mode);
            if($order['car']['attachment']) $order['car']['attachment']=array_merge($order['car']['getcar_img'],$order['car']['attachment']);
            else $order['car']['attachment']=$order['car']['getcar_img'];
        }
        if(!empty($order['car']['ot_carfare_img'])){
            $mode1=array('carfare_image');
            $order['car']['carfare_img'] = $this->etattachmentOut($order['car']['ot_carfare_img'],$mode1);
            if($order['car']['attachment']) $order['car']['attachment']=array_merge($order['car']['carfare_img'],$order['car']['attachment']);
            else $order['car']['attachment']=$order['car']['carfare_img'];
        }
        if($order['car']['et_attach'] && $order['car']['attachment']){
            $order['car']['attachment']=array_merge($order['car']['et_attach'],$order['car']['attachment']);
        }else if(empty($order['car']['ot_carcard_img']) && $estimae_msg){
            $order['car']['attachment']=$order['car']['et_attach'];
        }
        $order['owner']['credit'] = $order['buyer'];
//        if($order['car']['ot_assessment']>0){
//            $order['estimate']= $model->getOneRow('estimate', '*', array('`et_o_number` = ?' => $oid));
//            $order['car']['et_stime'] = $order['estimate']['et_stime'];
//            $order['car']['et_ftime'] = $order['estimate']['et_ftime'];
//        }

        /**
         * 重组返回
         */
        $order_info = array(
            'base' => $order,
            'owner' => $order['owner'], //车主信息
            'buyer' => $order['buyer'], //购车人征信信息
            'spouse' => $order['spouse'], //配偶信息 征信信息
            'guarantor' => $order['guarantor'], //担保人信息 征信信息
            'car' => $order['car'], //车辆信息
            'attachment' => $order['attachment'],
            'et_attach' => $order['car']['et_attach'],
            'audit_all' => $this->orderAudit($oid),
            'express' => $this->orderExpress($oid),
            'afteratt' => $this->afattachRe(array('`af_oid` = ?' => $oid)),
        );
        $order_info['audit'] = $this->orderReaudit($order_info);
        $msg = $model->getOneRow('order_oldinfo', '*', array('`o_id` = ?' => $oid));
        $order_info['oldinfo'] = $msg;
        $order_info['sign_money'] = (!empty($order['car']['ot_gps_no']) && $msg['o_ad_money'] > 0) || !empty($order['car']['ot_gps_status']) ? 1 : 0; //GPS为已上线，或者公司已垫款都无法更改GPS安装时间和GPS序列号。but:GPS为已上线、公司未垫款则可以清空GPS信息
        return $order_info;
    }

    /**
     * 获取订单的审核过程列表
     * @param type $oid
     * @return type
     */
    public function orderAudit($oid)
    {
        $model = $this->LoadModel('Public');
        $audit_all = $model->getList('order_audit', '*', array('`a_oid` = ?' => $oid));
        $re_data = array();
        if (!empty($audit_all)) {
            foreach ($audit_all as $k => $v) {
                $re_data[$v['a_status']][] = $v;
            }
        }

        return $re_data;
    }

    /**
     * 审核信息重组
     * @param type $order
     * @return type
     */
    public function orderReaudit($order)
    {   
        /*if(!empty($order['buyer']['ct_bairong_result'])){
            $vip_result = json_decode($order['buyer']['ct_bairong_result']);
            $order['buyer']['ct_bigdata'] = $this->unicodeDecode($vip_result->optimize_show);
            $order['buyer']['ct_bigdata_detail'] = $vip_result->url->detail_list;
            $order['buyer']['ct_bigdata_org'] = '百融金服';
        }*/
        $audit[] = array(
            'type' => '征信结果',
            'data' => array(
                'ct_name' => $order['buyer']['ct_name'],
                'ct_remark' => $order['buyer']['ct_remark'],
                'ct_key' => $order['buyer']['ct_key'],
                'ct_bigdata' => $order['buyer']['ct_bigdata']?$order['buyer']['ct_bigdata']:'',
                'ct_bigdata_number' => $order['buyer']['ct_bigdata_number']?$order['buyer']['ct_bigdata_number']:'',
                'ct_bigdata_org' => $order['buyer']['ct_bigdata_org']?$order['buyer']['ct_bigdata_org']:'',
                'ct_fico_result' => $order['buyer']['ct_fico_result']?unserialize($order['buyer']['ct_fico_result']): '',
            ),
            'dateline' => $order['buyer']['ct_dateline'],
            'search_time' => $order['base']['o_search_time'],
        );

        if (!empty($order['spouse'])) {
            /*if(!empty($order['spouse']['ct_bairong_result'])){
                $spouse_result = json_decode($order['spouse']['ct_bairong_result']);
                $order['spouse']['ct_bigdata'] = $this->unicodeDecode($spouse_result->optimize_show);
                $order['spouse']['ct_bigdata_detail'] = $spouse_result->url->detail_list;
                $order['spouse']['ct_bigdata_org'] = '百融金服';
            }*/
            $audit[] = array(
                'type' => '征信结果',
                'data' => array(
                    'ct_name' => $order['spouse']['ct_name'],
                    'ct_remark' => $order['spouse']['ct_remark'],
                    'ct_key' => $order['spouse']['ct_key'],
                    'ct_bigdata' => $order['spouse']['ct_bigdata']?$order['spouse']['ct_bigdata']:'',
                    'ct_bigdata_number' => $order['spouse']['ct_bigdata_number']?$order['spouse']['ct_bigdata_number']:'',
                    'ct_bigdata_org' => $order['spouse']['ct_bigdata_org']?$order['spouse']['ct_bigdata_org']:'',
                    'ct_fico_result' => $order['spouse']['ct_fico_result']?unserialize($order['spouse']['ct_fico_result']):'',
                ),
                'dateline' => $order['spouse']['ct_dateline'],
                'search_time' => $order['base']['o_search_time'],
            );
        }
        if (!empty($order['guarantor'])) {
            foreach ($order['guarantor'] as $k => $v) {
                /*if(!empty($v['ct_bairong_result'])){
                    $msg = json_decode($v['ct_bairong_result']);
                    $v['ct_bigdata'] = $this->unicodeDecode($msg->optimize_show);
                    $v['ct_bigdata_detail'] = $msg->url->detail_list;
                    $v['ct_bigdata_org'] = '百融金服';
                }*/
                $audit[] = array(
                    'type' => '征信结果',
                    'data' => array(
                        'ct_name' => $v['ct_name'],
                        'ct_remark' => $v['ct_remark'],
                        'ct_key' => $v['ct_key'],
                        'ct_bigdata' => $v['ct_bigdata']?$v['ct_bigdata']:'',
                        'ct_bigdata_number' => $v['ct_bigdata_number']?$v['ct_bigdata_number']:'',
                        'ct_bigdata_org' => $v['ct_bigdata_org']?$v['ct_bigdata_org']:'',
                        'ct_fico_result' => $v['ct_fico_result']?unserialize($v['ct_fico_result']):'',
                    ),
                    'dateline' => $v['ct_dateline'],
                    'search_time' => $order['base']['o_search_time'],
                );
            }
        }
        if (!empty($order['audit_all']['ok'])) {
            foreach ($order['audit_all']['ok'] as $k => $v) {
                if ($v['a_results'] == '通过') {
                    $type = '审核结果';
                } elseif ($v['a_results'] == '退回') {
                    $type = '退回情况';
                } else {
                    $type = '退单情况';
                }
                if($v['a_type'] == 'A00001终审审核'){
                    $v['a_type'] = '电话审核';
                }elseif($v['a_type'] == 'A00002终审审核'){
                    $v['a_type'] = '面签审核';
                }elseif($v['a_type'] == 'A00003终审审核'){
                    $v['a_type'] = '风险审核';
                }elseif($v['a_type'] == '初审审核'){
                    $v['a_type'] = '资料审核';
                }elseif($v['a_type'] == '复核审核'){
                    $v['a_type'] = '原件复合';
                }elseif($v['a_type'] == '征信过期退回' || $v['a_type'] == '征信过期,系统批量退回'){
                    $v['a_type'] = '征信过期退回';
                }else{
                    $v['a_type'] = '电话审核';
                }
                $audit[] = array(
                    'type' => $type,
                    'data' => array(
                        'a_dateline' => strtotime($v['a_dateline']),
                        'a_type' => $v['a_type'],
                        'a_results' => $v['a_results'],
                        'a_remarks' => $v['a_remarks'],
                        'a_details' => $v['a_details'],
                        'a_uname' => $v['a_uname'],
                    ),
                    'dateline' => strtotime($v['a_dateline']),
                );
            }
        }
        if (!empty($order['audit_all']['del'])) {
            foreach ($order['audit_all']['del'] as $k => $v) {
                if ($v['a_results'] == '通过') {
                    $type = '审核结果';
                } elseif ($v['a_results'] == '退回') {
                    $type = '退回情况';
                } else {
                    $type = '退单情况';
                }
                if($v['a_type'] == 'A00001终审审核'){
                    $v['a_type'] = '电话审核';
                }elseif($v['a_type'] == 'A00002终审审核'){
                    $v['a_type'] = '面签审核';
                }elseif($v['a_type'] == 'A00003终审审核'){
                    $v['a_type'] = '风险审核';
                }elseif($v['a_type'] == '初审审核'){
                    $v['a_type'] = '资料审核';
                }elseif($v['a_type'] == '复核审核'){
                    $v['a_type'] = '原件复合';
                }else{
                    $v['a_type'] = '电话审核';
                }
                $audit[] = array(
                    'type' => $type,
                    'data' => array(
                        'a_dateline' => strtotime($v['a_dateline']),
                        'a_type' => $v['a_type'],
                        'a_results' => $v['a_results'],
                        'a_remarks' => $v['a_remarks'],
                        'a_details' => $v['a_details'],
                        'a_uname' => $v['a_uname'],
                    ),
                    'dateline' => strtotime($v['a_dateline']),
                );
            }
        }
        $model = $this->LoadModel('Public');
        $stretch = $model->getList('stretch_rules', '*', array('`sr_oid` = ?' => $order['base']['o_id'], '`sr_result` != ?' => 'del'));
        if (!empty($stretch)) {
            foreach ($stretch as $k => $v) {
                $audit[] = array(
                    'type' => '通融情况',
                    'data' => array(
                        'sr_result' => $v['sr_result'],
                        'sr_cause' => $v['sr_cause'],
                        'sr_remark' => $v['sr_remark'],
                        'sr_idea' => $v['sr_idea'],
                        'sr_deal_time' => $v['sr_deal_time'],
                        'sr_deal_uname' => $v['sr_deal_uname'],
                        'sr_uname' => $v['sr_uname'],
                    ),
                    'dateline' => strtotime($v['sr_time']),
                );
            }
        }
        //按时间排序
        $sort = array('direction' =>'SORT_ASC','field' =>'dateline');
        $arrsort = array();
        foreach($audit AS $uniqid => $row){
            foreach($row AS $key=>$value){
                $arrSort[$key][$uniqid] = $value;
            }
        }
        if($sort['direction']){
            array_multisort($arrSort[$sort['field']], constant($sort['direction']), $audit);
        }
        return $audit;
    }

    public function auditRow($where)
    {
        $model = $this->LoadModel('Public');
        $audit_row = $model->getRow('order_audit', '*', $where, null, array('a_dateline DESC'));
        return $audit_row;
    }

    /**
     * 筛选出执行审核的最后记录 $key为a_type的可选值
     * @param type $arr
     * @param type $key
     * @return boolean
     */
    public function orderAuditfilter($arr, $key)
    {
        if (empty($arr)) {
            return false;
        }

        $re_arr = array();
        foreach ($arr as $k => $v) {
            if ($key == '终审审核' && strpos($v['a_type'], '终审审核')) {
                $re_arr[] = $v;
            } else {
                if ($v['a_type'] == $key) {
                    $re_arr[] = $v;
                }
            }
        }
        return $re_arr[count($re_arr) - 1];
    }

    /**
     * 获取订单物流信息
     * @param type $oid
     * @return type
     */
    public function orderExpress($oid)
    {
        $model = $this->LoadModel('Public');
        $audit_all = $model->getList('logistics', '*', array('`ls_oid` = ?' => $oid, '`ls_status` = ?' => 'ok'));
        if (!empty($audit_all)) {
            $audit_row = $audit_all[count($audit_all) - 1];
            if ($audit_row['ls_express_image']) {
                $audit_row['ls_express_image'] = unserialize($audit_row['ls_express_image']);
                $audit_row['ls_express_image_url'] = StringCode::doUrlimage($audit_row['ls_express_image']);
            }
        } else {
            $audit_row = array();
        }
        return $audit_row;
    }

    /**
     * 状态数值与文本转换
     * @param type $value
     * @param type $type
     * @return type
     */
    public function statusChange($value)
    {
        if (empty($value)) {
            return false;
        }
        $status_arr = array(
            '1' => '征信提交',
            '2' => '征信查询',
            '3' => '初审提交',
            '4' => '初审通过',
            '5' => '面签提交',
            '6' => '面签退单',
            '7' => '终审提交',
            '8' => '审核员审核通过',
            '9' => '终审通过',
            '10' => '作废',
            '11' => '退回',
            '12' => '已结清',
            '13' => '已成交',
            '14' => '审核中',
            '15' => '实时面签',
            '16' => '评估',
        );
        foreach ($status_arr as $k => $v) {
            if (is_numeric($value)) {
                if ($value == $k) {
                    return $v;
                    break;
                }
            } else {
                if ($value == $v) {
                    return $k;
                    break;
                }
            }
        }
        return false;
    }

    /**
     * 订单权限检测
     * @param type $oid
     * @param type $uid
     * @return type
     */
    public function checkOrderper($oid, $uid)
    {
        return array('success' => true, 'msg' => '允许操作');
    }

    /**
     * 换配偶做主贷人
     * @param type $oid
     * @return boolean
     */
    public function osExchange($oid)
    {
        $model = $this->LoadModel('Public');
        $order = $this->orderRow($oid);
        if (empty($order)) {
            return array('success' => false, 'msg' => '单号不存在');
        }

        $cert = $this->certAll(array(
            '`ct_status` = ?' => 'ok',
            '`ct_oid` = ?' => $order['o_id'],
            '`ct_key` IN (?)' => array('vip', 'spouse'),
        ));
        if (empty($cert)) {
            return array('success' => false, 'msg' => '信息不存在');
        }

        $check = false;
        foreach ($cert as $k => $v) {
            if ($v['ct_key'] == 'spouse') {
                $check = true;
                $spouse = $v;
                break;
            }
        }
        if (!$check) {
            return array('success' => false, 'msg' => '当前订单不存在配偶信息,无法更换配偶为主贷人');
        }
        $change_reg = array(
            'ct_spouse_degree' => 'ot_edu',
            'ct_spouse_province' => 'ot_residence_pro',
            'ct_spouse_city' => 'ot_residence_city',
            'ct_spouse_area' => 'ot_residence_area',
            'ct_spouse_mobile' => 'ot_mobile',
            'ct_spouse_liveadd' => 'ot_liveadd',
            'ct_spouse_tel' => 'ot_tel',
            'ct_spouse_company' => 'ot_company',
            'ct_spouse_cadd' => 'ot_company_add',
            'ct_spouse_ctel' => 'ot_company_tel',
            'ct_spouse_ctype' => 'ot_company_type',
            'ct_spouse_dutytp' => 'ot_duty_type',
            'ct_spouse_duty' => 'ot_duty',
            'ct_spouse_operatpd' => 'ot_operat_period',
            'ct_spouse_mincome' => 'ot_income_month',
        );
        $model->beginTransaction();
        if (!empty($cert)) {
            try {
                $owner_row = $model->getOneRow('order_owner', '*', array('`ot_oid` = ?' => $oid));
                foreach ($cert as $k => $v) {
                    if ($v['ct_key'] == 'vip') {
                        $new_detail = array(
                            'ct_spouse_id' => $v['ct_id'],
                        );
                        foreach ($change_reg as $rgkey => $rgval) {
                            $new_detail[$rgkey] = $owner_row[$rgval];
                        }
                        $model->update('order_cert', array('ct_key' => 'spouse', 'ct_detail' => serialize($new_detail)), array('`ct_id` = ?' => $v['ct_id']));
                    } else {
                        $model->update('order_cert', array('ct_key' => 'vip', 'ct_detail' => ''), array('`ct_id` = ?' => $v['ct_id']));
                        $order_data = array('o_vip_name' => $v['ct_name'], 'o_vip_card' => $v['ct_code']);
                    }
                }
                //更新车主表
                $spouse_detail = empty($spouse['ct_detail']) ? array() : unserialize($spouse['ct_detail']);
                $owner_data = array();
                foreach ($change_reg as $rgkey => $rgval) {
                    $owner_data[$rgval] = $spouse_detail[$rgkey];
                }
                $model->update('order_owner', $owner_data, array('`ot_oid` = ?' => $order['o_id']));
                if ($order_data) {
                    $model->update('order', $order_data, array('`o_id` = ?' => $order['o_id']));
                }
                $model->commit();
                return array('success' => true, 'msg' => '保存成功');
            } catch (Exception $ex) {
                $model->rollBack();
                return array('success' => false, 'msg' => '保存异常');
            }
        } else {
            return array('success' => false, 'msg' => '没有相关数据');
        }
    }

    /**
     * 作废订单
     * @param type $oid
     * @param type $isSuper 是否为补录页面操作
     * @return type
     */
    public function orderInvalid($oid, $isSuper=false)
    {
        $model = $this->LoadModel('Public');
        $order_row = $this->orderRow($oid);
        if (!$isSuper && (($order_row['o_suspend_status'] == 0 && $order_row['o_status'] == '审核中') || $order_row['o_status'] == '终审通过' || $order_row['o_status'] == '作废')) {
            return array('success' => false, 'msg' => '无法作废该订单');
        } else {
            $order = \wodrow\models\Order::findOne(array(array('=', 'o_id', $oid)));
            $msg = $order->getOrderOldinfo();
            if ($msg->o_ad_money>0){
                return array('success' => false, 'msg' => '公司已垫款无法作废');
            }
            if ($msg->o_bank_time>0){
                return array('success' => false, 'msg' => '银行已放款无法作废');
            }
            if($msg->o_lrid>0 && $msg->o_receivable>0){
                return array('success' => false, 'msg' => '已有财务数据无法作废');
            }
            if($msg->o_pact_totime>0){
                return array('success' => false, 'msg' => '已送银行无法作废');
            }
            $model->beginTransaction();
            try {
                $model->update('order', array('o_status' => '作废', 'o_quit_status' => $order_row['o_status']), array('`o_id` = ?' => $oid));
                $model->update('order_attachment', array('oa_status' => 'del'), array('`oa_oid` = ?' => $oid));
                $model->update('order_car', array('ot_status' => 'del','ot_gps_install' => '0000-00-00','ot_gps_no' => '','ot_gps_status' => '','ot_gps_remark' =>'','ot_gps_otime' => '0000-00-00'), array('`ot_oid` = ?' => $oid));
                $model->update('order_cert', array('ct_status' => 'del'), array('`ct_oid` = ?' => $oid));
                $model->update('order_owner', array('ot_status' => 'del'), array('`ot_oid` = ?' => $oid));
                $model->update('order_audit', array('a_status' => 'del'), array('`a_oid` = ?' => $oid));
                $model->update('order_up',array('up_status' => '作废'),array('`up_oid` =?'=>$oid,'`up_status` =?' =>'申请中'));
                $estimate_check  = $model->getOneRow('estimate','*',array('`et_o_number` = ?' => $oid));
                if(!empty($estimate_check)){
                    $model->update('estimate',array('et_status' => '已评估','et_o_number' =>''),array('`et_id` =?' => $estimate_check['et_id']));
                }
                if ($order_row['o_loan_money'] > 0) {
                    //增加同步任务
                    $model->save('task', array(
                        'task_type' => 'ordersync',
                        'task_releid' => $oid,
                        'task_addtime' => NOW_TIME,
                    ));
                }
                $model->commit();
                return array('success' => true, 'msg' => '保存成功');
            } catch (Exception $ex) {
                $model->rollBack();
                return array('success' => false, 'msg' => '保存异常' . $ex->getMessage());
            }
        }
        return array();
    }
    /**
     * 订单修改申请保存
     * @param type $data
     * @return type
     */
    public function orderupSave($data)
    {
        if (empty($data['oid'])) {
            return array('success' => false, 'msg' => '参数不全');
        }
        if (empty($data['base']) || empty($data['next']) || is_null($data['base_val']) || empty($data['now_val'])) {
            return array('success' => false, 'msg' => '参数不全');
        }
        $model = $this->LoadModel('Public');
        if (stripos($data['base'], 'guarantor') !== false) {
            $guarantor = explode('_', $data['base']);
            $g_id = empty($guarantor[1]) ? 0 : $guarantor[1];
            $info = $model->getOneRow('order_cert', '*', array('`ct_id` = ?' => $g_id));
            $data['base_text'] = '担保人_' . $info['ct_name'];
            $next = $this->modify_fields['guarantor'][$data['next']];
            $data['next_text'] = $next[0];
        }elseif(stripos($data['base'], 'spouse') !== false){
            $spouse = explode('_',$data['base']);
            $s_id = empty($spouse[1])? 0 : $spouse[1];
            $info = $model->getOneRow('order_cert','*',array('`ct_id` = ?' => $s_id));
            $data['base_text'] = '配偶_' . $info['ct_name'];
            $next = $this->modify_fields['spouse'][$data['next']];
            $data['next_text'] = $next[0];
        } else {
            $arr = array(
                'order' => '基本信息',
                'order_owner' => '购车人信息',
                'order_attachment' => '面签资料',
                'order_car' => '车辆信息',
            );
            $data['base_text'] = $arr[$data['base']];
            if ($data['base'] == 'order_attachment') {
                $info = $model->getOneRow('order', '*', array('`o_id` = ?' => $data['oid']));
                $mode_arr = $this->mode;
                $data['next_text'] = $mode_arr['attach_key'][$data['next']];
            } else {
                $next = $this->modify_fields[$data['base']][$data['next']];
                $data['next_text'] = $next[0];
            }
        }
        if($data['up_type'] =='type1'){
            $data['up_type'] = '主动';
        }elseif($data['up_type'] =='type2'){
            $data['up_type'] = '电审';
        }else{
            $data['up_type'] = '资审';
        }
        $data['up_info'] = serialize(array(
            'base' => $data['base'],
            'base_text' => $data['base_text'],
            'next' => $data['next'],
            'next_text' => $data['next_text'],
            'base_val' => $data['base_val'],
            'now_val' => $data['now_val'],
        ));
        $id = $model->save('order_up', $data);
        if ($id) {
            return array('success' => true, 'msg' => $id);
        } else {
            return array('success' => false, 'msg' => '参数不全');
        }
    }

    /**
     * 修改申请保存
     * @param type $data
     * @param type $where
     * @return type
     */
    public function orderupUpdate($data, $where = array(),$oid)
    {
        if (is_numeric($where)) {
            $where = array('`up_id` = ?' => $where);
        }
        $model = $this->LoadModel('Public');
        if($oid>0){
            $where = array('`up_oid` = ?' => $oid);
        }
        if (empty($where)) {
            $id = $model->save('order_up', $data);
            if ($id) {
                return array('success' => true, 'msg' => $id);
            } else {
                return array('success' => false, 'msg' => '保存失败');
            }
        } else {
            $model->update('order_up', $data, $where);
            return array('success' => true, 'msg' => '保存成功');
        }
    }

    /**
     * 获取修改项值
     * @param type $oid
     * @return type
     */
    public function ajaxMinfo($data)
    {
        if (empty($data['oid'])) {
            return array('success' => false, 'msg' => '参数不全');
        }
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order','*',array('`o_id` =?' => $data['oid']));
        if (empty($data['base']) && empty($data['next']) && empty($data['start'])) {
            $type = array(
                //'type1' => '主动',
                'type2' => '电审',
                'type3' => '资审'
                );
            $arr = array(
                'order' => '基本信息',
                'order_owner' => '购车人信息',
                'order_attachment' => '面签资料',
                'order_car' => '车辆信息',
            );
            $guarantor_all = $model->getList('order_cert', array('ct_id', 'ct_name'), array('`ct_oid` = ?' => $data['oid'], '`ct_key` = ?' => 'guarantor', '`ct_status` = ?' => 'ok'));
            if (!empty($guarantor_all)) {
                foreach ($guarantor_all as $k => $v) {
                    $arr['guarantor_' . $v['ct_id']] = '担保人_' . $v['ct_name'];
                }
            }
            $spouse_all = $model->getOneRow('order_cert', array('ct_id','ct_name'), array('`ct_oid` = ?' => $data['oid'], '`ct_key` = ?' => 'spouse', '`ct_status` = ?' => 'ok'));
            if(!empty($spouse_all)){
                $arr['spouse_'.$spouse_all['ct_id']] = '配偶_'. $spouse_all['ct_name'];
            }
            return array('success' => true, 'msg' => '', 'data' => $arr, 'type' => $type);
        } elseif (!empty($data['base'])) {
            $tab = $data['base'];
            if (stripos($data['base'], 'guarantor') !== false) {
                $tab = 'guarantor';
            }elseif(stripos($data['base'], 'spouse') !== false){
                $tab = 'spouse';
            }
            if (empty($data['next'])) {
                if ($data['base'] == 'order_attachment') {
                    $info = $model->getOneRow('order', '*', array('`o_id` = ?' => $data['oid']));
                    $mode_arr = $this->mode;
                    $mode_data = $mode_arr['mode'][$info['o_pre_mode']]['attachment'];
                    $value = array();
                    foreach ($mode_data as $k => $v) {
                        $value[$v] = array($mode_arr['attach_key'][$v], 3);
                    }
                    if($order_row['o_bank_id'] == 13){ //延中无法修改视频
                        unset($value['oa_video']);
                    }
                    return array('success' => true, 'msg' => '', 'data' => $value);
                } else {
                    if ($data['base'] == 'order_car') {
                        $car_info = $model->getOneRow('order_car', '*', array('`ot_oid` = ?' => $data['oid']));
                        $this->modify_fields['order_car']['ot_car_model'] = array('车型', 1, $car_info['ot_car_type']);
                    }
                    return array('success' => true, 'msg' => '', 'data' => $this->modify_fields[$tab]);
                }
            } else {
                //获取原先的值
                switch ($tab) {
                    case 'order':
                        $info = $model->getOneRow('order', '*', array('`o_id` = ?' => $data['oid']));
                        $value = $info[$data['next']];
                        break;
                    case 'order_owner':
                        $info = $model->getOneRow('order_owner', '*', array('`ot_oid` = ?' => $data['oid']));
                        $value = $info[$data['next']];
                        break;
                    case 'guarantor':
                        $guarantor = explode('_', $data['base']);
                        $g_id = empty($guarantor[1]) ? 0 : $guarantor[1];
                        $info = $model->getOneRow('order_cert', '*', array('`ct_id` = ?' => $g_id));
                        $info['ct_detail'] = unserialize($info['ct_detail']);
                        $value = $info['ct_detail'][$data['next']];
                        break;
                    case 'spouse':
                        $spouse = explode('_',$data['base']);
                        $s_id = empty($spouse[1])? 0 : $spouse[1];
                        $info = $model->getOneRow('order_cert','*',array('`ct_id` = ?' => $s_id));
                        $info['ct_detail'] = unserialize($info['ct_detail']);
                        $value = $info['ct_detail'][$data['next']];
                        break;
                    case 'order_attachment':
                        $msg = $model->getOneRow('order_attachment','*',array('`oa_oid` =?' => $data['oid']));
                        $value = unserialize($msg[$data['next']]);
                        break;
                    case 'order_car':
                        $info = $model->getOneRow('order_car', '*', array('`ot_oid` = ?' => $data['oid']));
                        $value = $info[$data['next']];
                        break;

                }
                return array('success' => true, 'msg' => '', 'data' => $value);
            }
        }
    }

    /**
     * 订单修改列表
     * @param type $where
     * @param type $page
     * @param type $limit
     * @param type $param
     * @param type $member
     * @return type
     */
    public function omList($where, $page = 1, $limit = PAGE_SIZE, $param = array())
    {
        $model = $this->LoadModel('Public');
        $data['count'] = $model->getRowCount('order_up', $where);
        if (!empty($data['count'])) {
            $data['all'] = $model->getList('order_up', '*', $where, array($page, $limit), null, array('up_id DESC'));
            Pagination::SetUrl($Param);
            $data['page'] = Pagination::GetHtml($limit, $page, $data['count']);
            $data['pagetotal'] = ceil($data['count'] / $limit);
        }
        return $data;
    }

    /**
     * 车辆信息
     * @param type $where
     * @return type
     */
    public function orderCar($where)
    {
        if (is_numeric($where)) {
            $where = array('`ot_oid` = ?' => $where);
        }
        $model = $this->LoadModel('Public');
        $data = $model->getOneRow('order_car', '*', $where);
        return $data;
    }

    /**
     * 根据修改单号
     * @param type $up_id
     * @return type
     */
    public function orderUp($data)
    {
        if (empty($data['up_id'])) {
            return array('success' => false, 'msg' => '参数不全');
        }
        $model = $this->LoadModel('Public');
        $up_row = $model->getOneRow('order_up', '*', array('`up_id` = ?' => $data['up_id']));
        if (empty($up_row)) {
            return array('success' => false, 'msg' => '未找到相关数据');
        }
        $up_row['up_info'] = unserialize($up_row['up_info']);
        $up_data = $up_row['up_info'];
        $model->beginTransaction();
        try {
            if ($data['up_status'] == '通过') {
                $model->save('task', array(
                    'task_type' => 'ordersync',
                    'task_releid' => $up_row['up_oid'],
                    'task_addtime' => NOW_TIME,
                ));
                if (stripos($up_data['base'], 'guarantor') !== false) {
                    $guarantor = explode('_', $up_data['base']);
                    $g_id = empty($guarantor[1]) ? 0 : $guarantor[1];
                    $info = $model->getOneRow('order_cert', '*', array('`ct_id` = ?' => $g_id));
                    $info['ct_detail'] = unserialize($info['ct_detail']);
                    foreach ($info['ct_detail'] as $k => $v) {
                        if ($up_data['next'] == $k) {
                            $info['ct_detail'][$k] = $up_data['now_val'];
                        }
                    }
                    $model->update('order_cert', array('ct_detail' => serialize($info['ct_detail'])), array('`ct_id` = ?' => $g_id));
                } elseif (stripos($up_data['base'], 'spouse') !== false){
                    $spouse = explode('_',$up_data['base']);
                    $s_id = empty($spouse[1])? 0 : $spouse[1];
                    $info = $model->getOneRow('order_cert','*',array('`ct_id` = ?' => $s_id));
                    $info['ct_detail'] = unserialize($info['ct_detail']);
                    foreach ($info['ct_detail'] as $k => $v){
                        if($up_data['next'] ==$k){
                            $info['ct_detail'][$k] = $up_data['now_val'];
                        }
                    }
                    $model->update('order_cert', array('ct_detail' => serialize($info['ct_detail'])), array('`ct_id` = ?' => $s_id));
                }elseif ($up_data['base'] == 'order') {
                    $model->update('order', array($up_data['next'] => $up_data['now_val']), array('`o_id` = ?' => $up_row['up_oid']));
                } elseif ($up_data['base'] == 'order_owner') {
                    $model->update('order_owner', array($up_data['next'] => $up_data['now_val']), array('`ot_oid` = ?' => $up_row['up_oid']));
                } elseif ($up_data['base'] == 'order_attachment') {
                    $info = $model->getOneRow('order_attachment', '*', array('`oa_oid` = ?' => $up_row['up_oid']));
                    $n_data = array();
                    if($data['up_id']<24714){
                        $n_data = unserialize($info[$up_data['next']]);
                    }
                    if (!empty($up_data['now_val'])) {
                        $exp_attach = explode(',', $up_data['now_val']);
                        foreach ($exp_attach as $upk => $upv) {
                            if (!empty($upv)) {
                                $n_data[] = $upv;
                            }
                        }
                    }
                    $model->update('order_attachment', array('' . $up_data['next'] . '' => serialize($n_data)), array('`oa_oid` = ?' => $up_row['up_oid']));
                    //20170609新增
                    $model->save('task', array(
                        'task_type' => 'ordersort',
                        'task_releid' => $up_row['up_oid'],
                        'task_addtime' => NOW_TIME,
                    ));
                } elseif ($up_data['base'] == 'order_car') {
                    $model->update('order_car', array($up_data['next'] => $up_data['now_val']), array('`ot_oid` = ?' => $up_row['up_oid']));
                }
            }
            $model->update('order_up', $data, array('`up_id` = ?' => $data['up_id']));
            $model->commit();
            return array('success' => true, 'msg' => '保存成功', 't_oid'=>$this->orderuping($up_row['up_oid'], '资审')>0?0:$up_row['up_oid'], 'a_oid'=>$this->orderuping($up_row['up_oid'], '电审')>0?0:$up_row['up_oid']);
        } catch (Exception $ex) {
            $model->rollBack();
            return array('success' => false, 'msg' => '保存异常' . $ex->getMessage());
        }
    }

    /**
     * 订单直接修改
     * @param type $data
     * @param type $where
     * @return type
     */
    public function orderdtSave($data, $where = '')
    {
        if (is_numeric($where)) {
            $where = array('`o_id` = ?' => $where);
        }
        $model = $this->LoadModel('Public');
        if (empty($where)) {
            $id = $model->save('order', $data);
            if ($id) {
                return array('success' => true, 'msg' => $id);
            } else {
                return array('success' => false, 'msg' => '保存失败');
            }
        } else {
            $roleModel->update('order', $data, $where);
            return array('success' => true);
        }
    }

    /**
     * 修改申请统计
     * @param type $where
     * @return type
     */
    public function orderupCount($where)
    {
        if (is_numeric($where)) {
            $where = array('`up_oid` = ?' => $where);
        }
        $model = $this->LoadModel('Public');
        $data = $model->getRowCount('order_up', $where);
        return $data;
    }

    /**
     * 检查修改申请订单
     * @param type $data
     * @return type
     */
    public function orderupCheck($data){
        if($data['start'] != 'type3' && $data['base'] == 'order_attachment' && $data['next'] == 'oa_contract'){
            return array('success' => false,'msg' => '合同照只能由资审申请修改');
        }
        $model = $this->LoadModel('Public');
        $up_msg = $model->getList('order_up','*',array('`up_oid` = ?' => $data['oid'],'`up_status` = ?' => '申请中'));
        for($i=0;$i<count($up_msg);$i++){
            $msg[$i] = unserialize($up_msg[$i]['up_info']);
            if(in_array($data['base'],$msg[$i]) && in_array($data['next'],$msg[$i])){
                return array('success'=> false, 'msg' => '该订单同样的修改项正在申请中');
            }
        }
            return array('success' => true, 'msg' => '可以修改');
    }

    /**
     * 订单修改信息
     * @param type $where
     * @return type
     */
    public function orderupRow($where)
    {
        if (is_numeric($where)) {
            $where = array('`up_oid` = ?' => $where);
        }
        $model = $this->LoadModel('Public');
        $data = $model->getRow('order_up', '*', $where);
        return $data;
    }

    /**
     * 获取订单修改未审核的个数
     * @param $id
     * @param $type
     * @return mixed
     */
    public function orderuping($id,$type='')
    {
        $where=array();
        $where['`up_oid`= ?']=$id;
        $where['`up_status`=?']='申请中';
        if($type=='资审'){
            $where['`up_type`= ?']=array('资审');
        }elseif($type == '电审'){
            $where['`up_type`= ?']=array('电审');
        }else{
            $where['up_info LIKE ?'] = '%视频类%';
        }
        $model = $this->LoadModel('Public');
        $count=$model->getRowCount('order_uping', $where);
        return $count;
    }

    public function carGetgps(){
        $model = $this->LoadModel('Public');
        $data = $model->getList('order_car', '*', array('`ot_gps_no` != ?' => '', '`ot_gps_status` != ?' => '已上线'));
        $updata = array('ot_gps_status' => '已上线', 'ot_gps_otime' => '2018-05-22');
        if(!empty($data)) foreach ($data as $k => $v){
            $r1 = \yii2api\classes\yii2api\Gps::getGps($v['ot_gps_no'], 0, serialize(array('o_add_time' => 0)));
            if ($r1->data->other_data->gps_status == '已上线') {
                $updata['ot_gps_otime'] = date("Y-m-d", $r1->data->other_data->gps_online_time);
                $result = $this->carUpdate($v['ot_oid'], $updata);
                file_put_contents(YII2API_PHP_SDK_DIR . "/yii2api/logs/gpsget.log", "\n\n\n" . date("Y-m-d H:i:s") . "\n" . $v['ot_oid'] . "\n".$updata['ot_gps_otime'], FILE_APPEND);
            }
        }
    }

    /**
     * 车辆信息补录
     * @return type
     */
    public function carUpdate($oid, $data)
    {
        if (!empty($data['ot_car_type'])) {
            $validator = Validator::checkRule($data, $this->car_rule);
            if (!$validator['pass']) {
                return array('success' => false, 'msg' => $validator['msg']);
            }
        }

        $model = $this->LoadModel('Public');

        //查询是否有car表记录没有则新增
        $car_check = $model->getOneRow('order_car', '*', array('`ot_oid` = ?' => $oid));
        $succ = true;
        $msg = '';
        if (isset($data['ot_gps_install'])) {
//GPS保存
            $validator = Validator::checkRule($data, $this->gps_rule);
            if (!$validator['pass']) {
                return array('success' => false, 'msg' => $validator['msg']);
            }
            $order_row = $model->getOneRow('order', '*', array('`o_id` = ?' => $oid));
            if (!empty($data['ot_gps_no'])) {
                $data['ot_gps_no'] = trim($data['ot_gps_no']);
                $o_br_name = $order_row['o_branch'];
                $first_check = $model->getList('order_car', '*', array('`ot_gps_no` = ?' => $data['ot_gps_no'], '`ot_oid` != ?' => $oid));
                if (count($first_check) > 0) {
                    $other_branch_check = $model->getOneRow('order_oldinfo', '*', array('`o_gps_no` = ?' => $data['ot_gps_no'], '`o_branch` != ?' => $o_br_name));
                    $branch_check = $model->getOneRow('order_oldinfo', '*', array('`o_gps_no` = ?' => $data['ot_gps_no'], '`o_branch` = ?' => $o_br_name, '`o_id` != ?' => $oid));
                    if (count($other_branch_check) > 0) {
                        return array('success' => false, 'msg' => 'GPS序号被其他网点占用，请联系公司');
                    } elseif (count($branch_check) > 0) {
                        $o_number = $branch_check['o_number'];
                        $other_order_msg = $model->getOneRow('order', '*', array('`o_number` = ?' => $o_number));
                        $u_name = $other_order_msg['o_vip_name'];
                        return array('success' => false, 'msg' => 'GPS已被本网点订单号为:' . $o_number . ',主贷人为:' . $u_name . '的订单占用');
                    }

                }
            }
            $o_vip = $model->getOneRow('order_owner', '*', array('`ot_oid` = ?' => $oid));
            $order_owner_row = $model->getOneRow('order_owner', '*', array('`ot_oid` = ?' => $oid));
            $car_id = '99' . str_pad($car_check['ot_id'], 6, '0', STR_PAD_LEFT);
            $_data = array(
                'client_name' => $order_row['o_branch'],
                'client_manager_mobile' => '',
                'plate_number' => '',
                'custom_name' => $order_row['o_vip_name'],
                'custom_mobile' => $o_vip['ot_mobile'], //主贷人手机号
                'o_add_time' => $order_row['o_add_time'], //征信发起时间
            );
            $_data = serialize($_data);
            $r = \yii2api\classes\yii2api\Gps::addGps($car_id, $data['ot_gps_no'], $_data);
            if ($r->code == 200) {
                $succ = isset($r->data->gps_response->other_data->success)?$r->data->gps_response->other_data->success:true;
                $msg = isset($r->data->gps_response->other_data->msg)?$r->data->gps_response->other_data->msg: '保存成功';
            } else {
                $succ = false;
                $msg = $r->message;
                if (strstr($r->message, '转移/销售设备失败，结果码：219')) {
                    $msg = '输入的GPS序列号不存在';
                }

            }
        }

        if ($succ) {
            if (empty($car_check)) {
                $data['ot_oid'] = $oid;
                $data['ot_status'] = 'ok';
                $data['ot_dateline'] = NOW_TIME;
                $model->save('order_car', $data);
            } else {
                $model->update('order_car', $data, array('`ot_oid` = ?' => $oid));
            }
            $model->save('task', array(
                'task_type' => 'ordercar',
                'task_releid' => $oid,
                'task_addtime' => NOW_TIME,
            ));
        }
        return array('success' => $succ, 'msg' => $msg);
    }

    /**
     * GPS信息清除
     * @param type $oid
     * @param type $data
     * @return type
     */
    public function gpsClean($oid)
    {
        $model = $this->LoadModel('Public');
        $money_check = $model->getOneRow('order_oldinfo', '*', array('`o_id` = ?' => $oid));
        if ($money_check['o_ad_money'] > 0) {
            return array('success' => false, 'msg' => '该订单已放款,无法撤销相关信息');
        } else {
            $msg = array(
                'ot_gps_install' => '',
                'ot_gps_no' => '',
                'ot_gps_remark' => '',
                'ot_gps_status' => '',
                'ot_gps_otime' => '',
            );
            $model->update('order_car', $msg, array('`ot_oid` = ?' => $oid));
            $model->save('task', array(
                'task_type' => 'ordercar',
                'task_releid' => $oid,
                'task_addtime' => NOW_TIME,
            ));
            return array('success' => true, 'msg' => '清除成功');
        }
    }

    /**
     * 初审占位
     * @param type $oid
     * @param type $member
     * @return type
     */
    public function perchJudge($oid, $member)
    {
        $model = $this->LoadModel('Public');
        $order_where = array('`o_id` = ?' => $oid);
        $order = $model->getOneRow('order', '*', $order_where);
        $o_trial_status = '审核中';        if($order['o_trial_status'] == '已通过'|| $order['o_trial_status']=='未通过') $o_trial_status = $order['o_trial_status'];
        $o_status = '审核中';        if($order['o_status'] != '初审提交') $o_status = $order['o_status'];
        if ($order['o_perch'] == 0) {
            $do = $model->update('order', array('o_perch' => $member['u_id'], 'o_perch_name' => $member['u_realname'], 'o_status' => $o_status, 'o_trial_status' => $o_trial_status), $order_where);
            return array('success' => true, 'msg' => '占位成功');
        } elseif ($order['o_perch'] > 0 && $order['o_perch'] != $member['u_id']) {
            $member = $model->getOneRow('member', array('u_realname'), array('`u_id` = ?' => $order['o_perch']));
            return array('success' => false, 'msg' => '当前订单已被' . $member['u_realname'] . '占位,您暂时无法处理');
        } elseif ($order['o_perch'] > 0 && $order['o_perch'] == $member['u_id']) {
            $do = $model->update('order', array('o_status' => $o_status, 'o_trial_status' => $o_trial_status), $order_where);
            return array('success' => true, 'msg' => '处理打开成功');
        } else {
            return array('success' => false, 'msg' => '失败');
        }
    }

    /**
     * 终审占位
     * @param type $oid
     * @param type $member
     * @return type
     */
    public function fperchJudge($oid, $member, $r_role_arr)
    {
        $model = $this->LoadModel('Public');
        $order_where = array('`o_id` = ?' => $oid);
        $order = $model->getOneRow('order', '*', $order_where);
        $o_layer_status = '审核中';        if($order['o_layer_status'] == '已通过' || $order['o_layer_status'] == '未通过') $o_layer_status = $order['o_layer_status'];
        $o_status = '审核中';        if($order['o_status'] != '初审提交') $o_status = $order['o_status'];
        //判断是否有电审开始时间
        $up_date = array();
        if($order['o_telstart_time'] == 0){
            $up_date['o_telstart_time'] = NOW_TIME;
        }
        $r_sign = in_array(97, $r_role_arr); //占位标记
        if ($order['o_final_perch'] == 0) {
            $up_date['o_final_perch'] = $member['u_id'];
            $up_date['o_status'] = $o_status;
            $up_date['o_layer_status'] = $o_layer_status;
            $do = $model->update('order', $up_date, $order_where);
            return array('success' => true, 'msg' => '占位成功');
        } elseif ($order['o_final_perch'] > 0 && $order['o_final_perch'] != $member['u_id'] && $r_sign != 1) {
            $member = $model->getOneRow('member', array('u_realname'), array('`u_id` = ?' => $order['o_final_perch']));
            return array('success' => false, 'msg' => '当前订单已被' . $member['u_realname'] . '占位,您暂时无法处理');
        } elseif ($order['o_final_perch'] > 0 && ($order['o_final_perch'] == $member['u_id'] || $r_sign == 1)) {
            $up_date['o_status'] = $o_status;
            $up_date['o_layer_status'] = $o_layer_status;
            $do = $model->update('order',$up_date,$order_where);
            return array('success' => true, 'msg' => '处理打开成功');
        } else {
            return array('success' => false, 'msg' => '失败');
        }
    }

    public function attachmentIn($data, $mode = 1, $check = false, $need_arr = true, $set_null = true)
    {
        $mode_arr = $this->loan_mode;
        $mode_arr = $mode_arr[$mode];
        $return_data = array();
        foreach ($mode_arr['attachment'] as $k => $v) {
            if ($check && empty($data[$v])) {
                return false;
                break;
            }
            if ($need_arr) {
                $return_data[$v] = $data[$v];
            } else {
                if ($set_null){
                    $return_data[$v] = serialize($data[$v]);
                }else{
                    if (isset($data[$v])){
                        $return_data[$v] = serialize($data[$v]);
                    }
                }
            }
        }
        return $return_data;
    }

    public function etattachmentOut($data,$mode='')
    {
        if($mode){
            $mode_arr=$mode;
        }else{
            $mode_arr = array('car', 'plate', 'comp');
        }
        $data=unserialize($data);
        $return_data = array();
        foreach ($mode_arr as $k => $v) {
            $return_data[$v] = empty($data[$v]) ? array() : $data[$v];
            $return_data[$v . '_url'] = empty($data[$v]) ? array() : StringCode::doUrlimage($return_data[$v]);
            if (!empty($return_data[$v])) {
                foreach ($return_data[$v] as $tkey => $tval) {
                    $file_name = end(explode('/', $tval));
                    $thumb_image = str_replace($file_name, 's_' . $file_name, $tval);
                    $return_data[$v . '_thurl'][$tkey] = is_file(WEB_PATH . $thumb_image) ? StringCode::doUrlimage($thumb_image) : StringCode::doUrlimage($tval);
                }
            }
        }
        return $return_data;
    }

    public function attachmentOut($data, $mode = 1)
    {
        $mode_arr = $this->loan_mode;
        $mode_arr = $mode_arr[$mode];
        $return_data = array();
        foreach ($mode_arr['attachment'] as $k => $v) {
            $return_data[$v] = empty($data[$v]) ? array() : unserialize($data[$v]);
            $return_data[$v . '_url'] = empty($data[$v]) ? array() : StringCode::doUrlimage($return_data[$v]);
            if (!empty($return_data[$v])) {
                foreach ($return_data[$v] as $tkey => $tval) {
                    $tval = str_replace('http://crm.app.qiche100.com', '', $tval);
                    $file_name = end(explode('/', $tval));
                    $thumb_image = str_replace($file_name, 's_' . $file_name, $tval);
                    $thumb_image = str_replace('http://crm.app.qiche100.com', '', $thumb_image);
                    $return_data[$v . '_thurl'][$tkey] = is_file(WEB_PATH . $thumb_image) ? StringCode::doUrlimage($thumb_image) : StringCode::doUrlimage($tval);
                }
            }
        }
        return $return_data;
    }

    public function getCardrt($card_val, $type = 'json')
    {
        $data = Config::GetCrd();
        if (!Validator::isIdcard($card_val)) {
            if ($type == 'json') {
                return array('success' => false, 'msg' => '身份证号错误');
            } else {
                return '';
            }
        }
        $card = array(
            'province' => $data[substr($card_val, 0, 2) . '0000'],
            'city' => $data[substr($card_val, 0, 4) . '00'],
        );
        if (substr($card_val, 4, 2) != '00') {
            $card['county'] = $data[substr($card_val, 0, 6)];
        }

        if (!$card['province']) {
            if ($type == 'json') {
                return array('success' => false, 'msg' => '身份证号错误');
            } else {
                return '';
            }
        }
        if ($type == 'json') {
            return array('success' => false, 'msg' => '获取成功', 'data' => $card);
        } else {
            return implode(" ", $card);
        }
    }

    public function changeMeans($key)
    {
        $arr = array(
            'fcard' => '身份证正面',
            'rcard' => '身份证反面',
            'auth' => '授权书',
            'sign' => '签字照',
        );
        return $arr[$key];
    }

    /**
     * 征信材料下载
     * @param type $cert_row
     */
    public function downCertdoc($cert_row)
    {
        $this->LoadResurces('PHPWord/PHPWord');
        $pw = new PHPWord();
        $section = $pw->createSection();
        $section->addText('征信资料', array('bold' => true, 'size' => 14), array('spacing' => 220, 'align' => 'center'));
        $styleTable = array('borderSize' => 6, 'borderColor' => '000000', 'cellMargin' => 80);
        $styleFirstRow = array('borderBottomSize' => 18, 'borderBottomColor' => '000000', 'bgColor' => 'ffffff');
        $pw->addTableStyle('myOwnTableStyle', $styleTable, $styleFirstRow);
        $fontStyle = array('bold' => false, 'align' => 'center', 'size' => 12);
        $rfontStyle = array('bold' => false, 'align' => 'right', 'size' => 12);
        $styleCell = array('valign' => 'center');
        $table = $section->addTable('myOwnTableStyle');
        $table->addRow(500);
        $table->addCell(3000, $styleCell)->addText('姓名：', $rfontStyle);
        $table->addCell(7000, $styleCell)->addText($cert_row['ct_name'], $fontStyle);
        $table->addRow(500);
        $table->addCell(3000, $styleCell)->addText('性别：', $rfontStyle);
        $table->addCell(7000, $styleCell)->addText($cert_row['ct_sex'], $fontStyle);
        $table->addRow(500);
        $table->addCell(3000, $styleCell)->addText('身份证号：', $rfontStyle);
        $table->addCell(7000, $styleCell)->addText($cert_row['ct_code'], $fontStyle);
        $table->addRow(500);
        $table->addCell(3000, $styleCell)->addText('身份证有效期：', $rfontStyle);
        $table->addCell(7000, $styleCell)->addText($cert_row['ct_validity_start'] . '-' . $cert_row['ct_validity_end'], $fontStyle);
        $table->addRow(500);
        $table->addCell(3000, $styleCell)->addText('出身年月：', $rfontStyle);
        $table->addCell(7000, $styleCell)->addText($cert_row['ct_birth'], $fontStyle);
        $table->addRow(500);
        $table->addCell(3000, $styleCell)->addText('身份证地址：', $rfontStyle);
        $table->addCell(7000, $styleCell)->addText($cert_row['ct_idaddress'], $fontStyle);

        if (!empty($cert_row['ct_attach'])) {
            foreach ($cert_row['ct_attach'] as $key => $val) {
                $table->addRow(1600);
                $table->addCell(3000, $styleCell)->addText($this->changeMeans($key) . '：', $rfontStyle);
                $img_file = '.'.$val;
                $address='/temp/credit_jpg/';
                $address1='temp/credit_jpg/';
                $imgSytle = $this->wordImg($img_file,450);
                $img=$this->word_img_zip($val,$imgSytle,WEB_PATH.$address);
                $img_yh=$address1.$img;
                $table->addCell(7000, $styleCell)->addImage($img_yh);
            }
        }
        $objWriter = PHPWord_IOFactory::createWriter($pw, 'Word2007');
        $ffname = iconv("utf-8", "gb2312", date('YmdHis_' . $cert_row['ct_name']));
        $doc_f = 'temp/credit_doc/' . $ffname . '.docx';
        $objWriter->save($doc_f);
        return $doc_f;
    }

    function image_jpg_zip($img,$address, $h = 450){
        if (!empty($img)) {
            $arr=array();
            foreach ($img as $key => $val) {
                $img_file = '.'.$val;
                $imgSytle = $this->wordImg($img_file,$h);
                $img=$this->word_img_zip($val,$imgSytle,WEB_PATH.$address);
                $arr[]=$address.$img;
            }
        }
        return $arr;
    }

    public function wordImg($img, $h = 450)
    {
        $w = $h*4/3;
        if (empty($img)) {
            return null;
        }

        $a = getimagesize($img);
        $s0 = $w / $h;
        $s1 = $a[0] / $a[1];
        $d=array(
            'width'=>$a[0],
            'height'=>$a[1]
        );
        if ($s0 >= $s1 && $a[1] > $h) {
            $d['height'] = $h;
            $d['width'] = $h / $a[1] * $a[0];
        }
        if ($s0 < $s1 && $a[0] > $w) {
            $d['width'] = $w;
            $d['height'] = $w / $a[0] * $a[1];
        }
        return $d;
    }

    function  word_img_zip($img, $imageStyle,$address){
        if($imageStyle == null)
            return $img;
        else{
            $FileFilter = pathinfo($img);
            $drr=WEB_PATH.$FileFilter['dirname'];
            $this->LoadResurces('image/class.image');
            $image = new Image($drr);
            $thumb_image = $image->thumb($FileFilter['basename'],$imageStyle['width'],$imageStyle['height'],'yh_',$address);
            return $thumb_image;
        }
    }

    /*public function downCertdexc($data){

        $this->LoadResurces('PHPExcel/PHPExcel');
        $objPHPExcel = new PHPExcel();

        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");

        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A6', '旧机动车鉴定评估委托书')
            ->setCellValue('F7', '     第         号')
            ->setCellValue('A8', '始峰二手车评估公司:')
            ->setCellValue('A9', '   因□交易□转籍□拍卖□置换■抵押□担保□咨询□司法 裁决，特委托你单位对以下车辆进行技术状况鉴定并出具评估报告书。')
            ->setCellValue('A11','附:委托评估车辆基本信息')
            ->setCellValue('A12', '车辆号牌')
            ->setCellValue('C12', '行驶证登记人名称')
            ->setCellValue('D12', '厂牌型号')
            ->setCellValue('F12', '初次登记日期')
            ->setCellValue('A13', $data['ot_car_platenum'])
            ->setCellValue('C13', $data['o_vip_name'])
            ->setCellValue('D13', $data['ot_carmodels'])
            ->setCellValue('F13', $data['ot_initialrg_time'])
            ->setCellValue('A14', '备注：无')
            ->setCellValue('A15', '填表说明：')
            ->setCellValue('A16', '1.若被评估车辆使用用途曾经为营运车辆，需要在备注栏中予以说明；')
            ->setCellValue('A18', '2.委托方必须对车辆信息的真实性负责，不得隐瞒任何情节，凡由此引起的法律责任及赔偿责任由委托方负责；')
            ->setCellValue('A24','委托方：易商新程（杭州）有限公司')
            ->setCellValue('D24','受托方：')
            ->setCellValue('E28','经办人(签字):')
            ->setCellValue('E30',date('Y').'  年  '.date('m').'  月  '.date('d').'  日  ')
            //二表部
            ->setCellValue('A33', '始峰二手车评估公司')
            ->setCellValue('B34', '评估作业表')
            ->setCellValue('A35', '车主')
            ->setCellValue('B35', $data['o_vip_name'])
            ->setCellValue('C35', '所有权性质')
            ->setCellValue('D35', '□公 ■私')
            ->setCellValue('E35', '联系电话')
            ->setCellValue('F35',$data['ot_mobile'])
            ->setCellValue('A36','住址')
            ->setCellValue('B36',$data['ot_home_add'])
            ->setCellValue('E36','经办人')
            ->setCellValue('A37','原始情况')
            ->setCellValue('E36','经办人')
            ->setCellValue('B37','厂牌型号')
            ->setCellValue('C37',$data['ot_carmodels'])
            ->setCellValue('D37','号牌号码')
            ->setCellValue('E37',$data['ot_car_platenum'])
            ->setCellValue('F37','车辆类型')
            ->setCellValue('G37',$data['ot_cartp'])
            ->setCellValue('B38','车辆识别代号(VIN)')
            ->setCellValue('C38',$data['ot_carno'])
            ->setCellValue('E38','车身颜色')
            ->setCellValue('F38',$data['ot_carcolor'])
            ->setCellValue('B39','发动机号')
            ->setCellValue('C39',$data['ot_engineno'])
            ->setCellValue('E39','登记证书编号')
            ->setCellValue('B40','总质量/座位/排量')
            ->setCellValue('E40','燃料种类')
            ->setCellValue('F40','汽油')
            ->setCellValue('B41','初次登记日期')
            ->setCellValue('C41',$data['ot_initialrg_time'])
            ->setCellValue('D41','车辆出厂日期')
            ->setCellValue('B42','已使用年限')
            ->setCellValue('D42','累积行驶里程')
            ->setCellValue('F42','使用用途')
            ->setCellValue('G42','非营运')
            ->setCellValue('A43','查核对易证件')
            ->setCellValue('B43','证件')
            ->setCellValue('B44','税费')
            ->setCellValue('C43','□原始发票■机动车登记证书■机动车行驶证■法人代码或身份证□其它')
            ->setCellValue('C44','■购置附加税□养路费■车船使用税□其它')
            ->setCellValue('A45','结构特点')
            ->setCellValue('A47','现时技术状况')
            ->setCellValue('B47','车况好，发动机及其它电气工作性能一切正常。无需修理或更换任何配件。')
            ->setCellValue('A49','维护保养状况')
            ->setCellValue('C49','定期保养')
            ->setCellValue('E49','现时状态')
            ->setCellValue('F49','良好')
            ->setCellValue('A50','价值反映')
            ->setCellValue('B50','账面原值(元)')
            ->setCellValue('B51','重置成本(元)')
            ->setCellValue('E50','车主报价(元)')
            ->setCellValue('D51','成新率(%)')
            ->setCellValue('F51','评估价格(元)')
            ->setCellValue('G51',$data['old_ot_assessment'])
            ->setCellValue('A52','鉴定评估目的：供抵押参考')
            ->setCellValue('A53','鉴定评估说明：重置成本×成新率=评估值')
            ->setCellValue('A54','注册二手车评估师（签名）')
            ->setCellValue('D54','复核人（签名）')
            ->setCellValue('A56',date('Y').'  年  '.date('m').'  月  '.date('d').'  日  ')
            ->setCellValue('D56',date('Y').'  年  '.date('m').'  月  '.date('d').'  日  ');
        //三表
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A1:D92')->getFont()->setName('宋体');
        $objPHPExcel->getActiveSheet()->getStyle('A6')->getFont()->setSize(20)->setBold(true);
        //$objPHPExcel->getActiveSheet()->getStyle('B42')->getFont()->setSize(17);
        //$objPHPExcel->getActiveSheet()->getStyle('A41')->getFont()->setSize(20)->setBold(true);
        //$objPHPExcel->getActiveSheet()->getStyle('A73')->getFont()->setSize(20)->setBold(true);
        //$objPHPExcel->getActiveSheet()->getStyle('A45')->getFont()->setSize(13);
        $objPHPExcel->getActiveSheet()->getStyle('A33')->getFont()->setSize(15)->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('A7:G30')->getFont()->setSize(10);
        $objPHPExcel->getActiveSheet()->getStyle('A8')->getFont()->setSize(11);
        $objPHPExcel->getActiveSheet()->getStyle('A9:G11')->getFont()->setSize(11);
        $objPHPExcel->getActiveSheet()->getStyle('A16:G19')->getFont()->setSize(11);
        $objPHPExcel->getActiveSheet()->getStyle('A24:G30')->getFont()->setSize(11);
        $objPHPExcel->getActiveSheet()->getStyle('A35:G56')->getFont()->setSize(10);
        $objPHPExcel->getActiveSheet()->getStyle('A74:D92')->getFont()->setSize(10);
        //对齐
        $objPHPExcel->getActiveSheet()->getStyle('A7:D15')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $objPHPExcel->getActiveSheet()->getStyle('A34:G42')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $objPHPExcel->getActiveSheet()->getStyle('A74:D90')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        //水平居中
        $objPHPExcel->getActiveSheet()->getStyle('A6')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A9')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $objPHPExcel->getActiveSheet()->getStyle('C20')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C26')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C32')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C24')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A33')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('B34')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A37')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A43:G56')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        $objPHPExcel->getActiveSheet()->getStyle('A73')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C86')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('C90')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直居中
        $objPHPExcel->getActiveSheet()->getStyle('A1:G92')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A6:G6');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('F7:G7');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A8:B8');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A9:G10');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A11:C11');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A12:B12');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A12:B12');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('F12:G12');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('F13:G13');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A13:B13');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('D13:E13');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('D12:E12');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A14:G14');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A15:D15');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A16:F17');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A18:G19');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A24:C24');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('D24:G24');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('C26:D26');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('E28:G28');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('E30:G30');

        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A33:G33');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('B34:F34');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('F35:G35');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('B36:D36');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('F36:G36');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A37:A42');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('C38:D38');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('F38:G38');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('C39:D39');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('F39:G39');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('C40:D40');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('F40:G40');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('E41:G41');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A43:A44');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('C43:G43');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('C44:G44');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A45:A46');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('B45:G46');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A47:A48');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('B47:G48');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A49:B49');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('C49:D49');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('F49:G49');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A50:A51');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('C50:D50');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A52:G52');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A53:G53');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A54:C54');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('D54:G54');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A56:C56');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('D56:G56');
        $objPHPExcel->setActiveSheetIndex(0)->mergeCells('F50:G50');
        //列宽
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(11);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(11);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(17);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(11.5);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10.5);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(8);
        //行高
        for($k=1;$k<=5;$k++){
            $objPHPExcel->getActiveSheet()->getRowDimension($k)->setRowHeight(17);
        }
        for($k=6;$k<=10;$k++){
            $objPHPExcel->getActiveSheet()->getRowDimension($k)->setRowHeight(27);
        }
        $objPHPExcel->getActiveSheet()->getRowDimension(11)->setRowHeight(17);
        for($k=12;$k<=15;$k++){
            $objPHPExcel->getActiveSheet()->getRowDimension($k)->setRowHeight(35);
        }
        for($k=33;$k<=42;$k++){
            $objPHPExcel->getActiveSheet()->getRowDimension($k)->setRowHeight(27);
        }
        $objPHPExcel->getActiveSheet()->getRowDimension(37)->setRowHeight(33);
        for($k=43;$k<=55;$k++){
            $objPHPExcel->getActiveSheet()->getRowDimension($k)->setRowHeight(24);
        }
        for($k=70;$k<=91;$k++){
            $objPHPExcel->getActiveSheet()->getRowDimension($k)->setRowHeight(33);
        }
        //设置单元格边框
        $objPHPExcel->getActiveSheet()->getStyle('A12:G14')->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);

        $objPHPExcel->getActiveSheet()->getStyle('A35:G54')->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);

        //设置自动换行
        $objPHPExcel->getActiveSheet()->getStyle('A1:D92')->getAlignment()->setWrapText(true);

        $objPHPExcel->getActiveSheet()->setTitle('评估报告');
        $objPHPExcel->setActiveSheetIndex(0);

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="哈尔滨工行评估报告.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory:: createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save( 'php://output');
        exit;
    }*/

    public function downCarword($data){
        $this->LoadResurces('PHPWord/PHPWord');
        $objPHPWord = new PHPWord();
        $objPHPWord->setDefaultFontName('宋体 (正文)');
        $styleTable = array('borderSize'=>6, 'borderColor'=>'000000', 'cellMargin'=>80);
        //一页
        $section = $objPHPWord->createSection(array('marginLeft'=>1600,'marginRight'=> 1600));
        $section->addText('目   录',array('bold'=>true, 'size'=>22,'name'=>'方正小标宋简体'),array('align'=>'center'));
        $section->addText(' ',array('bold'=>false, 'size'=>10.5));
        $section->addText('一、资产评估报告书',array('bold'=>true, 'size'=>15));
        $section->addText(' ',array('bold'=>false, 'size'=>5.5));
        $section->addText('   1、受托人鉴定评估类型',array('size'=>15));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('   2、评估目的',array('size'=>15));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('   3、评估对象及基本信息',array('size'=>15));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('   4、鉴定评估基准日',array('size'=>15));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('   5、评估依据',array('size'=>15));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('   6、评估方法',array('size'=>15));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('   7、评估过程',array('size'=>15));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('   8、评估结论',array('size'=>15));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('   9、特别事项说明',array('size'=>15));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('   10、评估报告法律效力',array('size'=>15));
        $section->addText(' ',array('size'=>15));
        $section->addText(' ',array('size'=>15));
        $section->addText(' ',array('size'=>15));
        $section->addText('二、附件',array('bold'=>true, 'size'=>15));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('   1、旧机动车鉴定评估委托书',array('size'=>15));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('   2、车辆行驶证复印件',array('size'=>15));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('   3、鉴定估价师职业资格证书复印件',array('size'=>15));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('   4、鉴定评估机构营业执照复印件',array('size'=>15));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('   5、旧机动车照片复印件',array('size'=>15));
        //二页
        $section->addPageBreak();
        $section->addText('旧机动车鉴定评估委托书',array('bold'=>true, 'size'=>18,'name'=>'方正小标宋简体'),array('align'=>'center'));
        $section->addText('2018第___号',array('bold'=>true, 'size'=>12),array('align'=>'right'));   
        $section->addText(' ',array('size'=>5.5));
        $section->addText('杭州始峰二手车鉴定评估有限公司：',array('size'=>14));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('    因□交易 转籍 □拍卖 □置换 ■抵押 □担保 □咨询 □司法裁决，特委托你单位对以下车辆进行技术状况鉴定并出具评估报告书。附：委托评估车辆基本信息',array('size'=>14),array('spacing' => 200));
        $objPHPWord->addTableStyle('myOwnTableStyle', $styleTable);
        $table = $section->addTable('myOwnTableStyle');
        $table->addRow(500);
        $table->addCell(2200,array('valign'=>'center'))->addText('车辆号牌',array('size'=>12),array('align'=>'center'));
        $table->addCell(2200,array('valign'=>'center'))->addText('行驶证登记人名称',array('size'=>12),array('align'=>'center'));
        $table->addCell(2200,array('valign'=>'center'))->addText('厂牌型号',array('size'=>12),array('align'=>'center'));
        $table->addCell(2200,array('valign'=>'center'))->addText('初次登记日期',array('size'=>12),array('align'=>'center'));
        $table->addRow(1100);
        $table->addCell(2200,array('valign'=>'center'))->addText($data['ot_car_platenum'],array('size'=>14),array('align'=>'center'));
        $table->addCell(2200,array('valign'=>'center'))->addText($data['o_vip_name'],array('size'=>14),array('align'=>'center'));
        $table->addCell(2200,array('valign'=>'center'))->addText($data['ot_car_model'],array('size'=>14),array('align'=>'center'));
        $table->addCell(2200,array('valign'=>'center'))->addText($data['ot_initialrg_time'],array('size'=>14),array('align'=>'center'));
        $table->addRow(400);
        $table->addCell(2200,array('cellMerge' => 'restart','valign'=>'center'))->addText('备注:',array('size'=>14));
        $table->addCell(2200, array('cellMerge' => 'continue'));
        $table->addCell(2200, array('cellMerge' => 'continue'));
        $table->addCell(2200, array('cellMerge' => 'continue'));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('填表说明:',array('size'=>14));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('1、若被评估车辆使用用途曾经为营运车辆，需在备注栏中予以说明；',array('size'=>14));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('2、委托方必须对车辆信息的真实性负责，不得隐瞒任何情节，凡由此引起的法律责任及赔偿责任由委托方负责；',array('size'=>14),array('spacing' => 200));
        $section->addText(' ',array('size'=>5.5),array('spacing' => 900));
        $section->addText('委托方：易商新程（杭州）有限公司     受托方：杭州始峰二手车鉴',array('size'=>14));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('                                               定评估有限公司',array('size'=>14));
        $section->addText(' ',array('size'=>5.5));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('                                      经办人（签字）：',array('size'=>14),array('spacing' => 100));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('                                   '.date("Y").'  年  '.date("m").'  月  '.date("d").'  日',array('size'=>14));
        //三页
        $section->addPageBreak();
        $section->addText('杭州始峰二手车鉴定评估有限公司',array('bold'=>true, 'size'=>22,'name'=>'方正小标宋简体'),array('align'=>'center'));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('评估作业表',array('bold'=>true, 'size'=>18),array('align'=>'center'));
        $section->addText(' ',array('size'=>5.5));
        $table1 = $section->addTable('myOwnTableStyle');
        $table1->addRow(350);
        $table1->addCell(1400,array('valign'=>'center'))->addText('车主',array('size'=>10));
        $table1->addCell(2600,array('cellMerge' => 'restart','valign'=>'center'))->addText($data['o_vip_name'],array('size'=>10));
        $table1->addCell(200, array('cellMerge' => 'continue'));
        $table1->addCell(2000,array('cellMerge' => 'restart','valign'=>'center'))->addText('所有权性质',array('size'=>10));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(2400,array('valign'=>'center'))->addText('□公  ■私',array('size'=>10));
        $table1->addCell(1800,array('cellMerge' => 'restart','valign'=>'center'))->addText('联系电话',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(1816,array('cellMerge' => 'restart','valign'=>'center'))->addText($data['ot_mobile'],array('size'=>10));
        $table1->addCell(700, array('cellMerge' => 'continue'));

        $table1->addRow(350);
        $table1->addCell(950,array('valign'=>'center'))->addText('住址',array('size'=>10));
        $table1->addCell(2600,array('cellMerge' => 'restart','valign'=>'center'))->addText($data['ot_home_add'],array('size'=>10));
        $table1->addCell(2200, array('cellMerge' => 'continue'));
        $table1->addCell(2200, array('cellMerge' => 'continue'));
        $table1->addCell(2200, array('cellMerge' => 'continue'));
        $table1->addCell(2200, array('cellMerge' => 'continue'));
        $table1->addCell(2200, array('cellMerge' => 'continue'));
        $table1->addCell(1300,array('cellMerge' => 'restart','valign'=>'center'))->addText('经办人',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(1816,array('cellMerge' => 'restart','valign'=>'center'))->addText(' ',array('size'=>10));
        $table1->addCell(700, array('cellMerge' => 'continue'));

        $table1->addRow(450);
        $table1->addCell(950, array('rowMerge' => 'restart', 'valign' => "center"))->addText('原      始     情    况 ',array('size'=>10));
        $table1->addCell(2600,array('valign'=>'center'))->addText('厂牌型号',array('size'=>10));
        $table1->addCell(400,array('cellMerge' => 'restart','valign'=>'center'))->addText($data['ot_car_model'],array('size'=>10));
        $table1->addCell(2000, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(1500,array('valign'=>'center'))->addText('号牌号码',array('size'=>10));
        $table1->addCell(1300,array('cellMerge' => 'restart','valign'=>'center'))->addText($data['ot_car_platenum'],array('size'=>9.5));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(1000,array('valign'=>'center'))->addText('车辆类型',array('size'=>9.5));
        $table1->addCell(700,array('valign'=>'center'))->addText(' ',array('size'=>10));

        $table1->addRow(350);
        $table1->addCell(950, array('rowMerge' => 'continue'));
        $table1->addCell(2600,array('cellMerge' => 'restart','valign'=>'center'))->addText('车辆识别代号(VIN)',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'restart','valign'=>'center'))->addText($data['ot_carno'],array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(1300,array('cellMerge' => 'restart','valign'=>'center'))->addText('车身颜色',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(1816,array('cellMerge' => 'restart','valign'=>'center'))->addText($data['ot_carcolor'],array('size'=>10));
        $table1->addCell(700, array('cellMerge' => 'continue'));

        $table1->addRow(350);
        $table1->addCell(950, array('rowMerge' => 'continue'));
        $table1->addCell(2600,array('cellMerge' => 'restart','valign'=>'center'))->addText('发动机号',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'restart','valign'=>'center'))->addText($data['ot_engineno'],array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(1300,array('cellMerge' => 'restart','valign'=>'center'))->addText('登记证号',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(1816,array('cellMerge' => 'restart','valign'=>'center'))->addText($data['ot_car_register'],array('size'=>10));
        $table1->addCell(700, array('cellMerge' => 'continue'));

        $table1->addRow(350);
        $table1->addCell(950, array('rowMerge' => 'continue'));
        $table1->addCell(2600,array('cellMerge' => 'restart','valign'=>'center'))->addText('总质量/座位/排量',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'restart','valign'=>'center'))->addText(' ',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(1300,array('cellMerge' => 'restart','valign'=>'center'))->addText('燃料种类',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(1816,array('cellMerge' => 'restart','valign'=>'center'))->addText('汽油',array('size'=>10));
        $table1->addCell(1100, array('cellMerge' => 'continue'));

        $table1->addRow(350);
        $table1->addCell(950, array('rowMerge' => 'continue'));
        $table1->addCell(2600,array('cellMerge' => 'restart','valign'=>'center'))->addText('初次登记日期',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800, array('valign'=>'center'))->addText($data['ot_initialrg_time'],array('size'=>10));
        $table1->addCell(800, array('valign'=>'center'))->addText('车辆出厂日期',array('size'=>10));
        $table1->addCell(2800,array('cellMerge' => 'restart','valign'=>'center'))->addText(' ',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'continue'));

        $table1->addRow(350);
        $table1->addCell(950, array('rowMerge' => 'continue'));
        $table1->addCell(2600,array('cellMerge' => 'restart','valign'=>'center'))->addText('已使用年限',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'restart','valign'=>'center'))->addText('  个月',array('size'=>10));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1600, array('valign'=>'center'))->addText('累计行驶里程',array('size'=>9.5));
        $table1->addCell(800, array('valign'=>'center'))->addText('       KM',array('size'=>10));
        $table1->addCell(1300,array('cellMerge' => 'restart','valign'=>'center'))->addText('使用用途',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'restart','valign'=>'center'))->addText('非营运',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));

        $table1->addRow(350);
        $table1->addCell(950,array('rowMerge' => 'restart','valign'=>'center'))->addText('查核对易证件',array('size'=>10));
        $table1->addCell(2600,array('cellMerge' => 'restart','valign'=>'center'))->addText('证件',array('size'=>10));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'restart','valign'=>'center'))->addText('□原始发票■机动车登记证书■机动车行驶证■法人代码或身份证□其它',array('size'=>10));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));

        $table1->addRow(350);
        $table1->addCell(950,array('rowMerge' => 'continue'));
        $table1->addCell(2600,array('cellMerge' => 'restart','valign'=>'center'))->addText('税费',array('size'=>10));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'restart','valign'=>'center'))->addText('■购置附加税□养路费■车船使用税□其它',array('size'=>10));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));

        $table1->addRow(550);
        $table1->addCell(950,array('valign'=>'left'))->addText('结构  特  点',array('size'=>10));
        $table1->addCell(2600,array('cellMerge' => 'restart','valign'=>'center'))->addText(' ',array('size'=>10));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));

        $table1->addRow(750);
        $table1->addCell(950,array('valign'=>'left'))->addText('现时  技 术 状  况',array('size'=>10));
        $table1->addCell(2600,array('cellMerge' => 'restart','valign'=>'center'))->addText('车况好，发动机及其它电气工作性能一切正常。无需修理或更换任何配件。',array('size'=>10));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'continue'));

        $table1->addRow(350);
        $table1->addCell(950, array('cellMerge' => 'restart','valign'=>'center'))->addText('维护保养情况',array('size'=>10));
        $table1->addCell(2600,array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('cellMerge' => 'restart','valign'=>'center'))->addText('定期保养 ',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'restart','valign'=>'center'))->addText('现时状态',array('size'=>10));
        $table1->addCell(1466,array('cellMerge' => 'restart','valign'=>'center'))->addText('良好',array('size'=>10));
        $table1->addCell(1816,array('cellMerge' => 'continue'));
        $table1->addCell(700,array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));

        $table1->addRow(350);
        $table1->addCell(950, array('rowMerge' => 'restart','valign'=>'center'))->addText('价值  反  映',array('size'=>10));
        $table1->addCell(2700,array('valign'=>'center'))->addText('账面原值(元)',array('size'=>10));
        $table1->addCell(2800,array('cellMerge' => 'restart','valign'=>'center'))->addText(' ',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(2400,array('cellMerge' => 'restart','valign'=>'center'))->addText('车主报价(元)',array('size'=>10));
        $table1->addCell(2400,array('cellMerge' => 'restart','valign'=>'center'))->addText(' ',array('size'=>10));
        $table1->addCell(700,array('cellMerge' => 'continue'));
        $table1->addCell(700,array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));

        $table1->addRow(350);
        $table1->addCell(950, array('rowMerge' => 'continue'));
        $table1->addCell(2600,array('cellMerge' => 'restart','valign'=>'center'))->addText('重置成本(元)',array('size'=>10));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(800, array('cellMerge' => 'continue'));
        $table1->addCell(1800,array('valign'=>'center'))->addText(' ',array('size'=>10));
        $table1->addCell(800, array('valign'=>'center'))->addText('成新率(%) ',array('size'=>10));
        $table1->addCell(800, array('valign'=>'center'))->addText('',array('size'=>10));
        $table1->addCell(1000, array('cellMerge' => 'restart','valign'=>'center'))->addText('评估价格(元)',array('size'=>10));
        $table1->addCell(1816,array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(800, array('valign'=>'center'))->addText($data['ot_assessment'],array('size'=>10));

        $table1->addRow(550);
        $table1->addCell(950, array('cellMerge' => 'restart','valign'=>'center'))->addText('鉴定评估目的：供抵押参考',array('size'=>10));
        $table1->addCell(2600, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));

        $table1->addRow(1050);
        $table1->addCell(950, array('cellMerge' => 'restart','valign'=>'center'))->addText('鉴定评估说明：重置成本×成新率＝评估值',array('size'=>10));
        $table1->addCell(2600, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));
        $table1->addCell(700, array('cellMerge' => 'continue'));

        $section->addText('      注册二手车评估师（签名）                               复核人（签名）',array('size'=>10));
        $section->addText(' ',array('size'=>5.5));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('      '.date('Y'). ' 年 '.date('m').' 月 '.date('d').' 日 '.'                               '.date('Y'). ' 年 '.date('m').' 月 '.date('d').' 日 ',array('size'=>10));
        
        //四页
        $section->addPageBreak();
        $section->addText('始峰评报字（2018）第___号',array('bold'=>true, 'size'=>12),array('align'=>'right'));
        $section->addText(' ',array('size'=>5.5));
        $section->addText('旧机动车鉴定评估报告书',array('bold'=>true, 'size'=>18),array('align'=>'center'));
        $section->addText(' ',array('size'=>5.5));
        $table2 = $section->addTable(array('borderSize'=>0, 'borderColor'=>'000000', 'cellMargin'=>80));
        $table2->addRow(450);
        $table2->addCell(255)->addText(' ',array('size'=>12));
        $table2->addCell(255)->addText(' ',array('size'=>12));
        $table2->addCell(300)->addText('杭',array('size'=>12));
        $table2->addCell(300)->addText('州',array('size'=>12));
        $table2->addCell(300)->addText('始',array('size'=>12));
        $table2->addCell(300)->addText('峰',array('size'=>12));
        $table2->addCell(300)->addText('二',array('size'=>12));
        $table2->addCell(300)->addText('手',array('size'=>12));
        $table2->addCell(300)->addText('车',array('size'=>12));
        $table2->addCell(300)->addText('鉴',array('size'=>12));
        $table2->addCell(300)->addText('定',array('size'=>12));
        $table2->addCell(300)->addText('评',array('size'=>12));
        $table2->addCell(300)->addText('估',array('size'=>12));
        $table2->addCell(300)->addText('有',array('size'=>12));
        $table2->addCell(300)->addText('限',array('size'=>12));
        $table2->addCell(300)->addText('公',array('size'=>12));
        $table2->addCell(300)->addText('司',array('size'=>12));
        $table2->addCell(300)->addText('接',array('size'=>12));
        $table2->addCell(300)->addText('受',array('size'=>12));
        $table2->addCell(3400)->addText(' 易商新程（杭州）有限公司 ',array('size'=>12,'underline'=>'single'));
        $section->addText('的委托，根据国家有关资产评估的规定，本着客观、独立、公正、科学的原则，按',array('size'=>12),array('spacing' => 100));
        $table8 = $section->addTable(array('borderSize'=>0, 'borderColor'=>'000000', 'cellMargin'=>100));
        $table8->addRow(450);
        $table8->addCell(8300)->addText('照公认的资产程序,对委托鉴定评估车辆进行了实地查勘与市场调查,并对其在',array('size'=>12));
        $table8->addCell(500)->addText('2018',array('size'=>12,'underline'=>'single'));
        $section->addText('年_'.date("m").'_月_'.date("d").'_日所表现的市场价值做出了公允反映。现将车辆评估情况及鉴定评估结果报告如下：',array('size'=>12),array('spacing' => 100));
        $section->addText('一、受托人及鉴定评估类型',array('bold'=>true, 'size'=>12),array('spacing' => 100));
        $section->addText('    始峰二手车评估公司工作人员接受国家劳动与社会保障部门组织的职业培训和鉴定，公司鉴定评估人员取得旧机动车鉴定评估职业资格证书。',array('size'=>12),array('spacing' => 100));
        $table8 = $section->addTable(array('borderSize'=>0, 'borderColor'=>'000000', 'cellMargin'=>100));
        $table8->addRow(450);
        $table8->addCell(2680)->addText('    评估人员证书编号：',array('size'=>12));
        $table8->addCell(5300)->addText('        樊辉              1617091906448000             ',array('size'=>12,'underline'=>'single'));
        $section->addText('二、评估目的',array('bold'=>true, 'size'=>12),array('spacing' => 100));
        $section->addText('    根据委托方的要求，本项目评估目的',array('size'=>12),array('spacing' => 100));
        $section->addText('    □交易  □转籍  □拍卖  □置换  ■抵押  □担保  □咨询  □司法裁决',array('size'=>12),array('spacing' => 100));
        $section->addText('三、评估依据',array('bold'=>true, 'size'=>12),array('spacing' => 100));
        $section->addText('    1、行为依据',array('size'=>12),array('spacing' => 100));
        $section->addText('        始峰评报字2018号第______号',array('size'=>12),array('spacing' => 100));
        $section->addText('    2、法律、法规依据。',array('size'=>12),array('spacing' => 100));
        $section->addText('     （1）《国有资产评估管理办法》（国务院令第91号）；',array('size'=>12),array('spacing' => 100));
        $section->addText('     （2）《摩托车报废标准暂行规定》（国家经贸委等部门令第33号）；',array('size'=>12),array('spacing' => 100));
        $section->addText('     （3）原国家国有资产管理局《关于印发〈国有资产评估管理办法施行细则〉',array('size'=>12),array('spacing' => 100));
        $section->addText('          的通知》（国资办发[1992]36号）；',array('size'=>12),array('spacing' => 100));
        $section->addText('     （4）原国家国有资产管理局《关于转发〈资产评估操作规范意见〉（试行）',array('size'=>12),array('spacing' => 100));
        $section->addText('          的通知》（国资办发[1996]32号）；',array('size'=>12),array('spacing' => 100));
        $section->addText('     （5）国家经贸委等部门《汽车报废报废标准》（国资办发[1997]456号）、',array('size'=>12),array('spacing' => 100));
        $section->addText('          《关于调整汽车报废标准若干规定的通知》（国经贸资源[2000]1202',array('size'=>12),array('spacing' => 100));
        $section->addText('          号、《农用运输车报废标准》）（国经贸资源[2001]234号）等；',array('size'=>12),array('spacing' => 100));
        $section->addText('     （6）《二手车流通管理办法》',array('size'=>12),array('spacing' => 100));
        $section->addText('     （7）其他相关的法律、法规等。',array('size'=>12),array('spacing' => 100));
        //五页
        $section->addPageBreak();
        $section->addText('四、评估方法',array('bold'=>true, 'size'=>12),array('spacing' => 130));
        $section->addText('    ■重置成本法   □现行市价法    □收益现值法    □其他',array('size'=>12),array('spacing' => 130));
        $section->addText('    根据本次评估的特定目的，确定公允的价格标准，采用重置成本法。即现时公开市场条件下重新购置或建造一个全新状态的被评估资产所需的全部成本减去被评估资产已经发生的各种贬值后得到的差额作为旧机动车评估值的一种方法。',array('size'=>12),array('spacing' => 130));
        $section->addText('五、评估过程',array('bold'=>true, 'size'=>12),array('spacing' => 130));
        $section->addText('    按照接受委托、验证、现场勘察、评定估算、提交报告的程序进行。',array('size'=>12),array('spacing' => 130));
        $section->addText('六、评估结论',array('bold'=>true, 'size'=>12),array('spacing' => 130));
        $table5 = $section->addTable(array('borderSize'=>0, 'borderColor'=>'000000', 'cellMargin'=>80));
        $table5->addRow(450);
        $table5->addCell(4500)->addText('   经过评定估算，车辆评估价值为人民币',array('size'=>12));
        $table5->addCell(1600)->addText(' '.$data['ot_assessment'].' ',array('size'=>12,'underline'=>'single'),array('align'=>'left'));
        $table5->addCell(700)->addText('元。',array('size'=>12),array('align'=>'left'));
        $table5->addRow(450);
        $table5->addCell(4600)->addText('   金额大写____________元整。',array('size'=>12));
        $section->addText('七、特别事项说明：',array('bold'=>true, 'size'=>12),array('spacing' => 130));
        $section->addText('   1、本次评估未考虑后期车辆处置、过户所需相关费用及税费。',array('size'=>12),array('spacing' => 130));
        $section->addText('   2、本次评估将应交规费及未接受处理的交通违法记录须缴罚金的估算数额（',array('size'=>12),array('spacing' => 130));
        $section->addText('      共计约____0____元）在评估中予以扣除。上述应交费用以主管部门确认的',array('size'=>12),array('spacing' => 130));
        $section->addText('      金额为准进行调整。',array('size'=>12),array('spacing' => 130));
        $section->addText('   3、评估基准日有效期以内资产数量发生变化，应根据原评估方法对资产额进',array('size'=>12),array('spacing' => 130));
        $section->addText('      行相应调整；如在评估有效期内被评估车辆的市场价格或因交通事故等原',array('size'=>12),array('spacing' => 130));
        $section->addText('      因导致车辆的价格变化，并对评估价产生明显影响时或，应及时聘请评估',array('size'=>12),array('spacing' => 130));
        $section->addText('      机构重新确定评估价。',array('size'=>12),array('spacing' => 130));
        $section->addText('八、评估报告法律效力',array('bold'=>true, 'size'=>12),array('spacing' => 130));
        $table7 = $section->addTable(array('borderSize'=>0, 'borderColor'=>'000000', 'cellMargin'=>80));
        $table7->addRow(450);
        $table7->addCell(5700)->addText('   1、本项评估结论有效期为90天，自评估基准日至',array('size'=>12));
        $table7->addCell(500)->addText(date('Y',NOW_TIME+7776000),array('size'=>12,'underline'=>'single'),array('align'=>'center'));
        $table7->addCell(300)->addText('年',array('size'=>12),array('align'=>'center'));
        $table7->addCell(300)->addText(date('m',NOW_TIME+7776000),array('size'=>12,'underline'=>'single'),array('align'=>'center'));
        $table7->addCell(300)->addText('月',array('size'=>12),array('align'=>'center'));
        $table7->addCell(300)->addText(date('d',NOW_TIME+7776000),array('size'=>12,'underline'=>'single'),array('align'=>'center'));
        $table7->addCell(300)->addText('日',array('size'=>12),array('align'=>'center'));
        $table7->addCell(500)->addText('止；',array('size'=>12),array('align'=>'center'));
        $section->addText('   2、评估报告只能由本评估报告载明的报告使用者用于载明的评估目的和用途；',array('size'=>12),array('spacing' => 130));
        $section->addText('      因评估报告书使用不当引起不良后果的，本公司不承担任何责任。',array('size'=>12),array('spacing' => 130));
        $section->addText('   3、本资产评估报告书未经本公司同意，报告的全部或部分内容不得发表于任',array('size'=>12),array('spacing' => 130));
        $section->addText('      何公开媒体上，法律、法规规定及相关当事方另有约定的除外。',array('size'=>12),array('spacing' => 130));
        $section->addText('   4、本项资产评估结果是反映对象在本次评估目的下，以公允价格进行的估价，',array('size'=>12),array('spacing' => 130));
        $section->addText('      未考虑国家宏观经济政策发生变化以及遇有自然力和其他不可抗力对资产',array('size'=>12),array('spacing' => 130));
        $section->addText('      价格的影响。当前述条件及评估中遵循的持续经营原则等其他情况发生变',array('size'=>12),array('spacing' => 130));
        $section->addText('      化时，评估结果失效。',array('size'=>12),array('spacing' => 130));
        //六页
        $section->addPageBreak();
        $section->addText(' ',array('size'=>5.5));
        $section->addText(' ',array('size'=>5.5));
        $table6 = $section->addTable(array('borderSize'=>0, 'borderColor'=>'000000', 'cellMargin'=>80));
        $table6->addRow(400);
        $table6->addCell(8500)->addText('  旧机动车鉴定评估委托书',array('size'=>12));
        $table6->addRow(400);
        $table6->addCell(8500)->addText('  车辆行驶证',array('size'=>12));
        $table6->addRow(400);
        $table6->addCell(8500)->addText('  鉴定估价师职业资格证书复印件',array('size'=>12));
        $table6->addRow(400);
        $table6->addCell(8500)->addText('  鉴定评估机构营业执照复印件',array('size'=>12));
        $table6->addRow(400);
        $table6->addCell(8500)->addText('  旧机动车照片',array('size'=>12));
        $table6->addRow(400);
        $table6->addCell(8500)->addText('  杭州始峰二手车鉴定评估有限公司',array('size'=>12));
        $table6->addRow(1200);
        $table6->addCell(8500)->addText(' ',array('size'=>12));
        $table6->addRow(900);
        $table6->addCell(8300)->addText('                                     注册旧机动车鉴定估价师（签字）：',array('size'=>12));
        $table6->addRow(900);
        $table6->addCell(8300)->addText('                                     复核人（签字）：',array('size'=>12));
        $table6->addRow(700);
        $table6->addCell(3000)->addText(' ',array('size'=>12),array('align'=>'right'));
        $section->addText('                                           日期： ' .date('Y'). ' 年 '.date('m').' 月 '.date('d').' 日 ',array('size'=>12),array('spacing' => 130));
        header("Content-type: application/vnd.ms-word");
        header('Content-Disposition:attachment;filename="'.$data['o_vip_name'].'的评估报告.'.'docx"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPWord_IOFactory:: createWriter($objPHPWord, 'Word2007');
        $objWriter->save( 'php://output');
        return true;
    }

    /**
     * 贷后资料保存
     * @param type $data
     * @param type $where
     * @return type
     */
    public function afattachSave($data, $where = '')
    {
        if (is_numeric($where)) {
            $where = array('`af_id` = ?' => $where);
        }
        $model = $this->LoadModel('Public');
        if (empty($where)) {
            $id = $model->save('order_after', $data);
            if ($id) {
                return array('success' => true, 'msg' => $id);
            } else {
                return array('success' => false, 'msg' => '保存失败');
            }
        } else {
            $id = $model->update('order_after', $data, $where);
            return array('success' => true);
        }
    }

    /**
     * 贷后资料
     * @param type $where
     * @return type
     */
    public function afattachRow($where)
    {
        if (is_numeric($where)) {
            $where = array(
                '`af_id` = ?' => $where,
            );
        }
        $model = $this->LoadModel('Public');
        return $model->getOneRow('order_after', '*', $where);
    }

    public function afattachAll($where)
    {
        if (is_numeric($where)) {
            $where = array(
                '`af_id` = ?' => $where,
            );
        }
        $model = $this->LoadModel('Public');
        return $model->getList('order_after', '*', $where);
    }

    public function afattachRe($where)
    {
        $data = $this->afattachAll($where);
        $re_data = array();
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $v['af_fileurl'] = StringCode::doUrlimage($v['af_file']);
                $re_data[$v['af_class']][] = $v;
            }
        }
        return $re_data;
    }
    /**
     * 面签资料
     * @param type $where
     * @return type
     */
    public function attachRow($where)
    {
        if (is_numeric($where)) {
            $where = array(
                '`oa_oid` = ?' => $where,
            );
        }
        $model = $this->LoadModel('Public');
        return $model->getRow('order_attachment', '*', $where);
    }
    /**
     * 更新面签资料
     * @param type $data
     * @param type $where
     * @return type
     */
    public function attachUpdate($data, $where = '')
    {
        if (is_numeric($where)) {
            $where = array(
                '`oa_oid` = ?' => $where,
            );
        }
        $model = $this->LoadModel('Public');
        return $model->update('order_attachment', $data, $where);
    }
    /**
     * 获取暂停订单的order_audit单条数据
     * @param type $oid
     * @param type $type 审核类型 fao代表终审，其他代表初审
     * @return type
     */
    public function getOneAudit($oid,$type){
        if($type == 'fao'){
            $a_type ='终审审核';
        }elseif($type == 'fto'){
            $a_type = '初审审核';
        }elseif($type == 'fvo'){
            $a_type = '视频审核';
        }
        if (is_numeric($oid)) {
            $where = array(
                '`a_oid` = ?' => $oid,
                '`a_results` = ?' => '暂停',
                '`a_type` = ?' => $a_type,
                '`a_status` =?' => 'ok'
            );
        }
        $model = $this->LoadModel('Public');
        return $model->getRow('order_audit','*', $where, null,array('a_id DESC'));
    }

    public  function  suspendMsg($oid){
        $order_row = $this->orderRow($oid);
        $o_suspend_remarks = '';
        if($order_row['o_suspend_status']==1) {
            if ($order_row['o_layer_status'] == '暂停中') {
                $audit_msg = $this->getOneAudit($order_row['o_id'], 'fao');
                if(!empty($audit_msg)) $o_suspend_remarks = $o_suspend_remarks."电审【".$order_row['o_final_perch_name'] . "】于" . $audit_msg['a_dateline'] . "暂停审核,原因为:\n" . $audit_msg['a_remarks'] . "\n";
            }
            if ($order_row['o_trial_status'] == '暂停中') {
                $audit_msg = $this->getOneAudit($order_row['o_id'], 'fto');
                if(!empty($audit_msg)) $o_suspend_remarks = $o_suspend_remarks."资审【".$order_row['o_perch_name'] . "】于" . $audit_msg['a_dateline'] . "暂停审核,原因为:\n" . $audit_msg['a_remarks'] . "\n";
            }
            if ($order_row['o_videoaudit_status'] == '暂停中') {
                $audit_msg = $this->getOneAudit($order_row['o_id'], 'fvo');
                if(!empty($audit_msg)){
                    $memeber_msg = $this->LoadModel('Public')->getOneRow('member','*',array('`u_id` =?' => $order_row['o_videoaudit_perch']));
                    $o_suspend_remarks = $o_suspend_remarks."视频审【".$memeber_msg['u_realname'] . "】于" . $audit_msg['a_dateline'] . "暂停审核,原因为:\n" . $audit_msg['a_remarks'] . "\n";
                }
            }
            $o_suspend_remarks = $o_suspend_remarks."如需继续审核请及时使用“订单申请修改”功能！";
        }
        if(!empty($o_suspend_remarks))
            return array(
                'm_uid' => $order_row['o_uid'],
                'm_title' => '暂停审核',
                'm_name' => $order_row['o_uname'],
                'm_content' => '您的客户'.$order_row['o_vip_name'] . '被'.$o_suspend_remarks,
                'm_dateline' => NOW_TIME,
                'm_oid' => $oid,
                'm_info' => serialize(array('status' => '暂停审核', 'code' => $this->statusChange('审核中'))),
            );
        else
            return null;
    }

    /**
     * 评估价
     * @param type $data
     */
    public function troCarData($data)
    {
        $model = $this->LoadModel('Public');
        $model->beginTransaction();
        try {
            $data['car']['ot_status'] = 'ok';
            $data['car']['ot_oid'] = $data['oid'];
            $data['car']['ot_dateline'] = NOW_TIME;
            $data['car']['ot_car_pose']=$data['ot_car_pose'];

            if($data['et_id']>0){
                $car=$model->getOneRow('estimate','*', array('`et_id` = ?' => $data['et_id']));
                //$arr=explode('-',$data['car_two1']);
                $data['car']['ot_car_type']=$car['et_car_type'];
                $data['car']['ot_car_model']=$car['et_car_model'];
                $data['car']['ot_assessment']=$car['et_price'];
                $data['car']['ot_assess_time']=date('Y-m-d',$car['et_ftime']);
                $data['car']['ot_mpac']=$car['et_fname'];
                $data['car']['ot_initialrg_time']=$car['et_car_date'];
                $data['car']['ot_car_fullmodel'] = $car['et_car_fullmodel'];
                $series_data = $model->getOneRow('car_series','*',array('`cs_car_text` =?' =>$car['et_car_model']));
                $data['car']['ot_car_seating'] = $car['et_seat_number'];
                if(!empty($series_data)){
                    $data['car']['ot_car_brand'] = $series_data['cs_car_brand'];
                }
                //$data['car']['ot_forecat_time']=date('Y-m-d',$car['et_stime']);
                $data['number']['et_o_number']=$data['oid'];
                $data['number']['et_status']='已使用';
                try{
                    $model->update('estimate',$data['number'],array('`et_id` = ?' => $data['et_id']));
                }catch (Exception $ex){}
            }
            $check = $model->getOneRow('order_car', array('ot_id'), array('`ot_oid` = ?' => $data['oid']));
            if (empty($check)) {
                $model->save('order_car', $data['car']);
            } else {
                $data['car']['ot_status'] = 'ok';
                $model->update('order_car', $data['car'], array('`ot_oid` = ?' => $data['oid']));
            }
            $model->commit();
            return array('success' => true, 'msg' => '保存成功');
        } catch (Exception $ex) {
            $model->rollBack();
            return array('success' => false, 'msg' => '保存异常');
        }
    }

    /**
     * 身份证地址查重
     * @param type $oid
     */
    public function idaddressCheck($oid){
        $model = $this->LoadModel('Public');
        //主贷人
        $vip_msg = $model->getOneRow('order_cert','*',array('`ct_oid` = ?' => $oid,'`ct_key` = ?' => 'vip'));
        if(!empty($vip_msg['ct_idaddress'])){
            $check_vip_cert = $model->getList('order_cert','*',array('`ct_oid` != ?' => $oid, '`ct_idaddress` = ?' => $vip_msg['ct_idaddress']));
            if(!empty($check_vip_cert)){
                for($i = 0; $i<count($check_vip_cert); $i++){
                    $check_vip_oid[$i] = $check_vip_cert[$i]['ct_oid'];
                    $vmsg = $model->getOneRow('order','*',array('`o_id` = ?' => $check_vip_oid[$i],'`o_bank_time` > ?' => 0));
                    if(!empty($vmsg) && ($vmsg['o_status']!= '作废' || $vmsg['o_quit_status'] =='退回')){
                        $check_vip_onumber[$i] = $vmsg['o_number'];
                        $check_vip_name[$i] = $check_vip_cert[$i]['ct_name'];
                    }
                }
                $result['check_vname'] = empty($check_vip_name)? '' : implode(',', $check_vip_name);
                $result['check_vnumber'] = empty($check_vip_onumber)? '' : implode(',', $check_vip_onumber);
            }
        }
        //配偶
        $spouse_msg =$model->getOneRow('order_cert','*',array('`ct_oid` = ?' => $oid,'`ct_key` = ?' => 'spouse'));
        if(!empty($spouse_msg) && !empty($spouse_msg['ct_idaddress'])){
            $check_spouse_cert = $model->getList('order_cert','*',array('`ct_oid` != ?' => $oid, '`ct_idaddress` = ?' => $spouse_msg['ct_idaddress']));
            if(!empty($check_spouse_cert)){
                for($a = 0; $a<count($check_spouse_cert); $a++){
                    $check_spouse_oid[$a] = $check_spouse_cert[$a]['ct_oid'];
                    $smsg = $model->getOneRow('order','*',array('`o_id` = ?' => $check_spouse_oid[$a],'`o_bank_time` > ?' => 0));
                    if(!empty($smsg) && ($smsg['o_status']!= '作废' || $smsg['o_quit_status'] =='退回')){
                        $check_spouse_onumber[$a] = $smsg['o_number'];
                        $check_spouse_name[$a] = $check_spouse_cert[$a]['ct_name'];
                    }
                }
            $result['check_sname'] = empty($check_spouse_name)? '' : implode(',', $check_spouse_name);
            $result['check_snumber'] = empty($check_spouse_onumber)? '' :implode(',', $check_spouse_onumber);
            }

        }
        //担保人
        $guarantor_msg = $model->getList('order_cert','*',array('`ct_oid` = ?' => $oid,'`ct_key` = ?' => 'guarantor'));
        if(!empty($guarantor_msg)){
            for($b = 0; $b<count($guarantor_msg); $b++){
                if(!empty($check_guarantor_cert[$b]['ct_idaddress'])){
                    $check_guarantor_cert[$b] = $model->getList('order_cert','*',array('`ct_oid` != ?' => $oid, '`ct_idaddress` = ?' => $guarantor_msg[$b]['ct_idaddress']));
                    if(!empty($check_guarantor_cert[$b])){
                        for($c = 0; $c<count($check_guarantor_cert[$b]);$c++){
                            $check_guarantor_oid[$b][$c] = $check_guarantor_cert[$b][$c]['ct_oid'];
                            $gmsg = $model->getOneRow('order','*',array('`o_id` = ?' => $check_guarantor_oid[$b][$c],'`o_bank_time` > ?' => 0));
                            if(!empty($gmsg) && ($gmsg['o_status']!= '作废' || $gmsg['o_quit_status'] =='退回')){
                                $check_guarantor_onumber[$b][$c] = $gmsg['o_number'];
                                $check_guarantor_name[$b][$c] = $check_guarantor_cert[$b][$c]['ct_name'];
                            }
                        }
                        $result['check_gname'][$b] = empty($check_guarantor_name[$b])? '' : implode(',' , $check_guarantor_name[$b]);
                        $result['check_gnumber'][$b] = empty($check_guarantor_onumber[$b])? '' : '担保人'.$guarantor_msg[$b]['ct_name'].'与订单号为'.implode(','     , $check_guarantor_onumber[$b]);
                    }else{
                        $result['check_gname'][$b] = '';
                        $result['check_gnumber'][$b] = '';
                    }
                }
            }
        }
        return $result;
    }

    /**
     * 获取合同条款与审核配置
     * @param type $oid
     */
    public function contractDetails($oid){
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order','*',array('`o_id` = ?' => $oid));
        $branch_id = $order_row['o_branch_id'];
        $branch_row = $model->getOneRow('branch','*',array('`br_id` = ?' => $branch_id));
        if(!empty($branch_row['br_audit_details'])){
            $branch_msg['audit_details'] =  $branch_row['br_audit_details'];
        }else{
            if($branch_row['br_audit_value'] >=10){
                $branch_msg['audit_details'] = $branch_row['br_audit_value'].'万（含）以下简审';
            }elseif($branch_row['br_audit_value'] == 0){
                $branch_msg['audit_details'] = '无简审';
            }else{
                $branch_msg['audit_details'] = $branch_row['br_audit_value'].'万（含）以下双免简审';
            }
        }
        $contract_row = $model->getRow('branch_contract','*',array('`bc_brid` = ?' => $branch_id,'`bc_status` = ?' => 'ok'), null,array('bc_id DESC'));
        $branch_msg['contract'] = $contract_row['bc_details'];
        $image = unserialize($contract_row['bc_contract_image']);
        if(!empty($image['sign_image'])){
            $msg = explode('/',$image['sign_image'][0]);
            $msg[4] = 's_'.$msg[4];
            $branch_msg['sign_img'] = BASE_ATTACH.implode('/',$msg);
            $branch_msg['sign_image'] = BASE_ATTACH.$image['sign_image'][0]; 
        }
        return $branch_msg;
    }

    /**
     * 手机号查重
     * @param type $oid
     */
    public function phoneCheck($oid){
        $model = $this->LoadModel('Public');
        //主贷人
        $vip_msg = $model->getOneRow('order_cert','*',array('`ct_oid` = ?' => $oid,'`ct_key` = ?' => 'vip'));
        if(!empty($vip_msg['ct_mobile'])){
            $check_vip_cert = $model->getList('order_cert','*',array('`ct_oid` != ?' => $oid, '`ct_mobile` = ?' => $vip_msg['ct_mobile']));
            if(!empty($check_vip_cert)){
                for($i = 0; $i<count($check_vip_cert); $i++){
                    $check_vip_oid[$i] = $check_vip_cert[$i]['ct_oid'];
                    $vmsg = $model->getOneRow('order','*',array('`o_id` = ?' => $check_vip_oid[$i],'`o_bank_time` > ?' => 0));
                    if(!empty($vmsg) && ($vmsg['o_status']!= '作废' || $vmsg['o_quit_status'] =='退回')){
                        $check_vip_onumber[$i] = $vmsg['o_number'];
                        $check_vip_name[$i] = $check_vip_cert[$i]['ct_name'];
                    }
                }
                $result['check_phone_vname'] = empty($check_vip_name)? '' : implode(',', $check_vip_name);
                $result['check_phone_vnumber'] = empty($check_vip_onumber)? '' : implode(',', $check_vip_onumber);
            }
        }
        //配偶
        $spouse_msg =$model->getOneRow('order_cert','*',array('`ct_oid` = ?' => $oid,'`ct_key` = ?' => 'spouse','`ct_status` != ?' => 'del'));
        if(!empty($spouse_msg) && !empty($spouse_msg['ct_mobile'])){
            $check_spouse_cert = $model->getList('order_cert','*',array('`ct_oid` != ?' => $oid, '`ct_mobile` = ?' => $spouse_msg['ct_mobile']));
            if(!empty($check_spouse_cert)){
                for($a = 0; $a<count($check_spouse_cert); $a++){
                    $check_spouse_oid[$a] = $check_spouse_cert[$a]['ct_oid'];
                    $smsg = $model->getOneRow('order','*',array('`o_id` = ?' => $check_spouse_oid[$a],'`o_bank_time` > ?' => 0));
                    if(!empty($smsg) && ($smsg['o_status']!= '作废' || $smsg['o_quit_status'] =='退回')){
                        $check_spouse_onumber[$a] = $smsg['o_number'];
                        $check_spouse_name[$a] = $check_spouse_cert[$a]['ct_name'];
                    }
                }
            $result['check_phone_sname'] = empty($check_spouse_name)? '' : implode(',', $check_spouse_name);
            $result['check_phone_snumber'] = empty($check_spouse_onumber)? '' :implode(',', $check_spouse_onumber);
            }
        }
        //担保人
        $guarantor_msg = $model->getList('order_cert','*',array('`ct_oid` = ?' => $oid,'`ct_key` = ?' => 'guarantor','`ct_status` = ?' =>'ok'));
        if(!empty($guarantor_msg)){
            for($b = 0; $b<count($guarantor_msg); $b++){
                if(!empty($guarantor_msg[$b]['ct_mobile'])){
                    $check_guarantor_cert[$b] = $model->getList('order_cert','*',array('`ct_oid` != ?' => $oid, '`ct_mobile` = ?' => $guarantor_msg[$b]['ct_mobile']));
                    if(!empty($check_guarantor_cert[$b])){
                        for($c = 0; $c<count($check_guarantor_cert[$b]);$c++){
                            $check_guarantor_oid[$b][$c] = $check_guarantor_cert[$b][$c]['ct_oid'];
                            $gmsg = $model->getOneRow('order','*',array('`o_id` = ?' => $check_guarantor_oid[$b][$c],'`o_bank_time` > ?' => 0));
                            if(!empty($gmsg) && ($gmsg['o_status']!= '作废' || $gmsg['o_quit_status'] =='退回')){
                                $check_guarantor_onumber[$b][$c] = $gmsg['o_number'];
                                $check_guarantor_name[$b][$c] = $check_guarantor_cert[$b][$c]['ct_name'];
                            }
                        }
                        $result['check_phone_gname'][$b] = empty($check_guarantor_name[$b])? '' : implode(',' , $check_guarantor_name[$b]);
                        $result['check_phone_gnumber'][$b] = empty($check_guarantor_onumber[$b])? '' : '担保人'.$guarantor_msg[$b]['ct_name'].'与订单号为'.implode(',' , $check_guarantor_onumber[$b]);
                    }else{
                        $result['check_phone_gname'][$b] = '';
                        $result['check_phone_gnumber'][$b] = '';
                    }
                }
            }
        }
        return $result;
    }

    public function virtualTask($o_number, $task_type){
        $model = $this->LoadModel('Public');
        $order = $model->getOneRow('order', 'o_id', array('`o_number` = ?' => $o_number));
        return $task = array(
            array(
                'task_id' => 0,
                'task_type' => $task_type,
                'task_releid' => $order['o_id'],
                'task_info' => '',
                'task_status' => 'no',
                'task_addtime' => time(),
                'task_dotime' => 0
            )
        );
    }

    /**
     * 车资照与提车影像提交
     * @param type $oid
     * @return type
     */
    public function carimgSubmit($oid,$u_realname){
        $model = $this->LoadModel('Public');
        $car_msg = $model->getOneRow('order_car','*',array('`ot_oid` =?' =>$oid));
        if($car_msg['ot_carfare_img'] == '' || $car_msg['ot_getcar_img'] == ''){
            return array('succ' => false,'msg'=> '该订单的车资照和提车影像至少有一项没任何图片,请确认是否已保存');
        }else{
            $data=array(
                'ot_image_date' => NOW_TIME,
                'ot_image_user' => $u_realname,
                'ot_image_status' => '已提交'
            );
            $model->update('order_car',$data,array('`ot_oid` =?' => $oid));
            return array('succ' => true,'msg' => '提交成功');
        }
    }

    /**
     * 获取订单最新的A0001审核结果
     * @param type $oid
     * @return type
     */
    public function getFinalresult($oid,$type=''){
        $model = $this->LoadModel('Public');
        if(empty($type)){
            $final_msg = $model->getRow('order_audit', '*', array('`a_oid` = ?' => $oid, '`a_type` = ?' => 'A00001终审审核','`a_results` =?' =>'通过'), null, array('a_id DESC'));
        }elseif($type == 'A00001终审审核' || $type == 'A00003终审审核'){
            $final_msg = $model->getRow('order_audit', '*', array('`a_oid` = ?' => $oid, '`a_type` = ?' => $type ,'`a_status` =?' =>'ok'), null, array('a_id DESC'));
        }else{
            $final_msg = $model->getRow('order_audit', '*', array('`a_oid` = ?' => $oid, '`a_type` = ?' => 'A00001终审审核','`a_results` =?' =>'通过','`a_details` LIKE ?' => '%'.$type.'%'), null, array('a_id DESC'));
        }
        return $final_msg;
    }

    /**
     * 20180314
     * 多余附件标记删除，做了标记的计划任务执行删除
     * @param type $oid
     * @return boolean
     */
    public function attachCheck($oid){
        if(empty($oid)) return false;
        $model = $this->LoadModel('Public');
        $order_att_tab = $model->getOneRow('order_attachment', array('oa_cert','oa_assets','oa_family','oa_sign','oa_flowing','oa_other','oa_contract','oa_singlecard'), array('`oa_oid` = ?' => $oid));
        $att_image = array();
        if(!empty($order_att_tab)) foreach($order_att_tab as $k => $v){
            $att_arr = empty($v) ? array() : unserialize($v);
            if(!empty($att_arr)) foreach($att_arr as $key => $val){
                if(in_array($val, $att_image))                    continue;
                $att_image[] = $val;
            }
        }
        $temp_att = $model->getList('attachment', '*', array('`ot_oid` = ?' => $oid, '`delete_status` = ?' => 0));
        $model->beginTransaction();
        try{
            if(!empty($temp_att)) foreach($temp_att as $k => $v){
                if(!in_array($v['url'], $att_image)){
                    $model->update('attachment', array('delete_status' => 1), array('`at_id` =?' => $v['at_id']));
                }
            }
            $model->commit();
            return true;
        } catch (Exception $ex) {
            $model->rollBack();
            return false;
        }


    }

    //写入attachment中征信上传图片的oid
    public function updateAttachoid($oid,$temp_id){
        if(empty($oid) || empty($temp_id)) return false;
        $model = $this->LoadModel('Public');
        try{
            $result = $model -> update('attachment',array('ot_oid' => $oid,'temp_id' =>0),array('`temp_id` =?' =>$temp_id,'`delete_status` =?' => 0));
        } catch (Exception $ex){
            return false;
        }
        return $result;

    }
    //绑定评估时写入oid
    public function updateAttachestimate($oid,$et_id){
        if(empty($oid) || empty($et_id)) return false;
        if($oid > 0 && $et_id > 0){
            $model = $this->LoadModel('Public');
            try{
              $result = $model -> update('attachment',array('ot_oid' => $oid),array('`temp_id` =?' =>$et_id,'`delete_status` =?' => 0));
            } catch (Exception $ex){
                return false;
            }
            return $result;
        }else{
            return false;
        }

    }

    public function dothurl($data){
        if(!empty($data)){
            foreach($data as $k=>$v){
                $msg = substr_replace($v,'s_',18,0);
                $result[$k] = BASE_ATTACH.$msg;
            }
            return $result;
        }

    }

    //按文件名排序
    public function sortattachment($data,$oid){
        $model = $this->LoadModel('Public');
        $img_arr = $model->getList('attachment','*',array('`ot_oid` =?' => $oid,'`url` IN (?)' => $data));
        $sort = array('direction' =>'SORT_ASC','field' =>'image_name');
        $arrsort = array();
        foreach($img_arr AS $uniqid => $row){
            foreach($row AS $key=>$value){
                $arrSort[$key][$uniqid] = $value;
            }
        }
        if($sort['direction']){
            array_multisort($arrSort[$sort['field']], constant($sort['direction']), $img_arr);
        }
        foreach($img_arr as $k => $v){
            $result[] = $v['url'];
        }
        return $result;

    }

    //视频审占位判断
    public function videoperJudge($oid,$member_info){
        if(empty($oid) || empty($member_info)){
            return array('success' => false,'msg' => '缺少参数');
        }
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order','*',array('`o_id` =?' => $oid));
        $o_videoaudit_status = ($order_row['o_videoaudit_status'] == '已通过' || $order_row['o_videoaudit_status'] == '未通过') ? $order_row['o_videoaudit_status'] : '审核中';
        $o_status = $order_row['o_status'] != '初审提交' ? $order_row['o_status'] : '审核中';
        if ($order_row['o_videoaudit_perch'] == 0) {
            $do = $model->update('order', array('o_videoaudit_perch' => $member_info['u_id'],'o_status' => $o_status, 'o_videoaudit_status' => $o_videoaudit_status), array('`o_id` =?' => $oid));
            return array('success' => true, 'msg' => '占位成功');
        }elseif($order_row['o_videoaudit_perch'] >0 && $order_row['o_videoaudit_perch'] != $member_info['u_id'] && $member_info['u_role'] != 16){
            $member = $model->getOneRow('member', array('u_realname'), array('`u_id` = ?' => $order_row['o_videoaudit_perch']));
            return array('success' => false, 'msg' => '当前订单已被' . $member['u_realname'] . '占位,您暂时无法处理');
        }elseif($order_row['o_videoaudit_perch'] >0 && ($order_row['o_videoaudit_perch'] == $member_info['u_id'] || $member_info['u_role'] == 16 )){ //16为电审经理权限id
            $do = $model->update('order',array('o_status' => $o_status,'o_videoaudit_status' => $o_videoaudit_status),array('`o_id` =?' => $oid));
            return array('success' => true, 'msg' =>'打开成功');
        }else{
            return array('success' => false, 'msg' =>'失败');
        }


    }

    //视频审核
    public function videoAudit($data,$oid){
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order', '*', array('`o_id` = ?' => $oid));
        if (empty($order_row)) {
            return array('success' => false, 'msg' => '订单不存在');
        }

        if (!in_array($order_row['o_status'], array('初审提交', '审核中')) && $order_row['o_videoaudit_status'] != '未审核') {
            return array('success' => false, 'msg' => '当前订单状态不允许初审操作');
        }
        $model->beginTransaction();
        try {
            if ($data['a_uid']) {
                $member_row = $model->getOneRow('member', array('u_realname'), array('`u_id` = ?' => $data['a_uid']));
                $data['a_uname'] = $member_row['u_realname'];
            }
            $data['a_results'] = $data['a_results'] == '可以办理' ? '通过' : '退单';
            if($data['draft'] == false){
                if($data['a_results'] == '通过'){
                    $data['a_type'] = 'A00002终审审核';
                    $order_data = array('o_videoaudit_status' =>'已通过', 'o_videoaudit_time' => NOW_TIME,'o_video_auditor' =>$data['a_uid']);
                if($order_row['o_layer_status'] =='已通过' && $order_row['o_trial_status'] =='已通过'){
                    $order_data['o_status'] = '终审通过';
                    $model->save('task',array(
                        'task_type' => 'ordersync',
                        'task_releid' => $oid,
                        'task_addtime' => NOW_TIME,
                    ));
                }
                }else{
                    $order_data = array('o_videoaudit_status' =>'未审核','o_trial_status' => '未审核','o_layer_status' => '未审核', 'o_layer_aucode' => '', 'o_status' => '退回','o_videoaudit_time' => NOW_TIME, 'o_quit_status' => $order_row['o_status'], 'o_quit_time' => NOW_TIME);
                }
                $order_data['o_videoaudit_time'] = NOW_TIME;
                $model->update('order',$order_data,array('`o_id` =?' =>$oid));
                $log_data = array(
                    'log_uid' => $data['a_uid'],
                    'log_action' => 'video_audit',
                    'log_related_id' => $oid,
                    'log_explain' => '视频审核',
                    'log_dateline' => NOW_TIME,
                );
                $model->save('order_log', $log_data);
                $data['a_status'] = 'ok';
            }else{
                $data['a_status'] = 'draft';
            }
            //$data['a_type'] = '视频审核';
            $data['a_oid'] = $oid;
            $data['a_dateline'] = date('Y-m-d H:i:s');
            $data['a_info'] = serialize($order_row);
            $model->save('order_audit', $data);
            $model->commit();
            return array('success' => true, 'msg' => '保存成功');
        } catch (Exception $ex) {
            $model->rollBack();
            return array('success' => false, 'msg' => '保存异常');
        }

    }

    //电审回退到上一级审核员
    public function auditAgain($oid,$member_info,$remark=''){
        if(empty($oid)) return array('success' => false ,'msg'=>'缺少参数');
        $model =$this->LoadModel('Public');
        $order_row = $model->getOneRow('order', '*', array('`o_id` = ?' => $oid));
        $model->beginTransaction();
        try {
            $order_audit = array(
                'a_oid' => $oid,
                'a_type' => 'A00003终审审核',
                'a_results' =>'退回',
                'a_remarks' =>$remark,
                'a_uid' => $member_info['u_id'],
                'a_uname' => $member_info['u_realname'],
                'a_dateline' => date('Y-m-d H:i:s'),
                'a_status' => 'ok',
                'a_info' => serialize($order_row)
            );
            $model->save('order_audit', $order_audit);
            $log_data = array(
                'log_uid' => $member_info['u_id'],
                'log_action' => 'final_audit',
                'log_related_id' => $oid,
                'log_explain' => 'A00003终审审核',
                'log_dateline' => NOW_TIME,
            );
            $model->save('order_log', $log_data);
            $audit_msg = $this->getFinalresult($oid);
            $order_data = array(
                'o_last_perch' => $member_info['u_id'],
                'o_layer_aucode' => '',
                'o_web_risk' => 0,
                'o_rebate_per' => 0,
                'o_needgps' => 0,
                'o_final_perch' => $audit_msg['a_uid']
            );
            $model -> update('order',$order_data,array('`o_id` =?' =>$oid));
            $model->commit();
            return array('success' => true, 'msg' => '保存成功');
        } catch (Exception $ex) {
            $model->rollBack();
            return array('success' => false, 'msg' => '保存异常');
        }
    }


    /**
     * 得到有文件名、上传人、上传时间的排序后某订单某分类的附件列表
     * @param $attsArray 无排序无文件名的附件数组
     * @param $oid 订单ID
     * @param $class 分类
     */
    public function  getAttsList($attsArray, $oid, $class)
    {
        $model = $this->LoadModel('Public');
        $img_arr = $model->getList('attachment', '*', array('`ot_oid` = ?' => $oid, '`class` = ?' => $class, '`delete_status` =?' => 0));
    }


    /**
     * 面签通过的单子在初审单提交时，写入面签通过
     * @param $u_name 审核人名字
     * @param $oid 订单ID
     * @param $time 通过时间
     */
    public function videoResult($oid,$u_name,$time,$url){
        $model = $this->LoadModel('Public');
        $audit_row = $model->getRow('order_audit','*',array('`a_oid`=?' => $oid,'`a_results` =?' =>'退回'),null,array('a_id DESC'));
        $a_id = empty($audit_row)? 0 : $audit_row['a_id'];
        $check_msg = $model->getOneRow('order_audit','*',array('`a_oid`=?' =>$oid,'`a_type`=?' => 'A00002终审审核','`a_results`=?' => '通过','`a_id` >?' => $a_id));
        if(empty($check_msg)){
            $member_msg = $model->getOneRow('member','*',array('`u_realname` =?' => $u_name));
            $order_row = $model->getOneRow('order','*',array('`o_id` =?' => $oid));
            $model->beginTransaction();
            try{
                $order_data = array(
                    'o_videoaudit_status' => '已通过',
                    'o_videoaudit_time' => strtotime($time),
                    'o_videoaudit_perch' => $member_msg['u_id'],
                    'o_video_auditor' => $member_msg['u_id']
                );
                $audit_data = array(
                    'a_oid' => $oid,
                    'a_type' => 'A00002终审审核',
                    'a_results' => '通过',
                    'a_details' => '银行面签审核通过',
                    'a_uid' => $member_msg['u_id'],
                    'a_uname' => $u_name,
                    'a_dateline' =>date('Y-m-d H:i:s',NOW_TIME),
                    'a_status' => 'ok',
                    'a_info' => serialize($order_row)
                );
                if(empty($member_msg)){
                    $audit_data['a_remarks'] = '通过人为：'.$u_name;
                }
                $log_data = array(
                    'log_uid' => $member_msg['u_id'],
                    'log_action' => 'video_audit',
                    'log_related_id' => $oid,
                    'log_explain' => '银行面签视频审核',
                    'log_dateline' => strtotime($time)
                );
                $model->update('order_attachment',array('oa_video' => serialize(array($url))),array('`oa_oid` =?' =>$oid));
                $model->update('order',$order_data,array('`o_id` =?' =>$oid));
                $model->save('order_audit',$audit_data);
                $model->save('order_log', $log_data);
                $model->commit();
                return array('success' => true, 'msg' => '保存成功');
            }catch (Exception $ex) {
                $model->rollBack();
                return array('success' => false, 'msg' => '保存异常');
            }
        }else{
            return array('success' =>true ,'msg' =>'已存在信息');
        }
    }


    /**
     * 电审占位
     * @param $oid 订单号
     * @param $type 类型
     */
    public function telPerch($oid,$type){
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order','*',array('`o_id` =?' =>$oid));
        if($type == 'submit'){
            $audit_where = array(
                '`a_oid` =?' => $oid,
                '`a_status` =?' =>'ok'
            );
            $member_where = array(
                '`u_status` =?' =>'ok'
            );
            if($order_row['o_loan_money'] <= 80000){ //小单中单轮流
                $audit_where['`a_type` IN (?)'] = array('A00003终审审核','终审审核');
                $member_where['`u_auditlevel` IN (?)'] = array(5,6);
            }else{
                $audit_where['`a_type` IN (?)'] = array('A00001终审审核','终审审核');
                if($order_row['o_loan_money'] < 200000){//小单轮流
                    $member_where['`u_auditlevel` =?'] = 5;
                }else{
                    $member_where['`u_auditlevel` =?'] = $order_row['o_loan_money'] <300000 ? 6 : 7; //20-30W 中单轮流 大于30 大单轮流
                }
            }
            $audit_msg = $model->getRow('order_audit','*',$audit_where,null,array('a_id DESC'));
            if(empty($audit_msg)){
                $member_msg = $model->getRow('member','*',$member_where,null,array('u_order_count ASC'));
                $model->update('order',array('o_final_perch' =>$member_msg['u_id']),array('`o_id` =?' =>$oid));
                $model->update('member',array('u_order_count' =>$member_msg['u_order_count'] +1),array('`u_id` =?' =>$member_msg['u_id']));
            }else{
                $model->update('order',array('o_final_perch' =>$audit_msg['a_uid']),array('`o_id` =?' =>$oid));
            }
        }else{
            $audit_msg = $model->getRow('order_audit','*',array('`a_oid` =?' =>$oid,'`a_status` =?' =>'ok','`a_type` =?' =>'A00003终审审核'),null,array('a_id DESC'));
            if(!empty($audit_msg)){
                $model->update('order',array('o_final_perch' => $audit_msg['a_uid']),array('`o_id` =?' =>$oid));
            }else{
                $au_msg = $model->getRow('setting_audit','*',array('`au_status` =?' =>'ok','`au_ceiling` >=?' => $order_row['o_loan_money']/10000),null,array('au_ceiling ASC'));
                $member_arr = $model->getList('member','*',array('`u_auditlevel` =?' =>$au_msg['au_id'],'`u_status` =?' =>'ok'));
                $count = count($member_arr);
                $key = rand(0,$count-1);
                $model->update('order',array('o_final_perch' =>$member_arr[$key]['u_id']),array('`o_id` =?' =>$oid));
            }
        }

    }

    /**
     * 查询垫款状态
     * @param $oid 订单号
     */
    public function querystate($oid){
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order','*',array('`o_id` =?' => $oid));
        $msg = explode('-',$order_row['o_number']);
        $br_code = $msg[0];
        $branch_msg = $model->getOneRow('ysjr_workgroup','*',array('`wg_bh` =?' =>$br_code));
        if($branch_msg['wg_black'] == '黑名单'){
            return array('success' => true,'msg' => '你网点已被列入黑名单，如有疑问请联系运营总监');
        }
        if($branch_msg['wg_stop'] == 2){
            return array('success' => true ,'msg' => '你网点已被停款，请查看<待处理列表>');
        }
        $oldorder_info = $model->getOneRow('order_oldinfo','*',array('`o_id` =?' =>$oid));
        switch ($order_row['o_status']){
            case '审核中':
                return array('success' => true ,'msg' => '该订单尚未完成审核，请至<待审核>列表查看，关注是否审核暂停');
                break;
            case '退回':
                return array('success' => true,'msg' => '该订单审核被拒，如有疑问请提交<通融申请>');
                break;
            case '作废':
                return array('success' => true,'msg' => '该订单已作废');
                break;
            case '终审通过':
                if($oldorder_info['o_adtime'] > 0){
                    $bank_time = date('Y-m-d', strtotime($oldorder_info['o_adtime']));
                    return array('success' => true, 'msg' => '该订单已于'.$bank_time.'垫款，请稍后确认是否到账');
                }
                $car_row = $model->getOneRow('order_car','*',array('`ot_oid` =?' => $oid));
                if($car_row['ot_car_pose'] == '二手车'){
                    if(empty($car_row['ot_2check_date'])){
                        return array('success' => true,'msg' => '该订单为二手车，登记证书未传或评估未确认，请至<车辆信息补录>查看');
                    }
                    if($order_row['o_needgps'] == 1 && $car_row['ot_gps_status']!='已上线'){
                        return array('success' => true,'msg' => '该订单风控判定需要安装GPS，GPS序列号未登记或者未获取到上线状态，请至<车辆信息补录>操作，若有疑问请联系合作服务部');
                    }
                }
                $audit_row = $model->getOneRow('order_audit','*',array('`a_details` =?' => '通融通过不垫资','`a_oid` =?' => $oid,'`a_status`=?' => 'ok'));
                if(!empty($audit_row) && !($oldorder_info['o_bank_time']>0)){
                    return array('success' => true ,'msg' => '该订单风控判定通融通过不垫款，请等待银行放款');
                }
                if(empty($oldorder_info['o_lrid']) || $order_row['o_needpay'] == 1){
                    return array('success' => true , 'msg' => '该订单财务尚未操作，请等待');
                }
                if($oldorder_info['o_lrid'] > 0){
                    return array('success' => true ,'msg' => '该订单财务正在操作垫款，请等待');
                }
                return array('success' => true , 'msg' =>'该订单终审通过');
                break;
            case '初审提交':
                return array('success' => true ,'msg' => '订单已提交，但未有审核人员进行审核');
                break;
            default:
                return array('success' => true ,'msg' => '该订单尚未提交或被审核退回');
        }
    }

    //获取一条审核记录
    public function getAudit($where){
        if (is_numeric($where)) {
            $where = array('`a_id` = ?' => $where);
        }
        $where['`a_status`=?'] = 'ok';
        $model = $this->LoadModel('Public');
        $result = $model->getRow('order_audit','*',$where,null,array('a_id DESC'));
        return $result;
    }


    public function object2array_pre(&$object) {
        if (is_object($object)) {
            $arr = (array)($object);
        } else {
            $arr = &$object;
        }
        if (is_array($arr)) {
            foreach($arr as $varName => $varValue){
                $arr[$varName] = $this->object2array($varValue);
            }
        }
        return $arr;
    }   
    public  function object2array(&$object) {
        $object =  json_decode( json_encode( $object),true);
        return  $object;
    }

    /**
     * 征信重查
     * @param $data 相关数据
     * @param $oid 订单号
     * @param $oid 操作人信息
     */
    public function creditBack($data,$oid,$member_info){
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order','*',array('`o_id` =?' =>$oid));
        //图片替换
        $credit_list = $this->certList(array('`ct_oid` =?' =>$oid,'`ct_status`=?' =>'ok'));
        foreach($credit_list as $k => $v){
            if($v['ct_code'] == $data['o_vip_card']){
                $v['ct_attach']['auth'] = $data['o_vip_auth'];
            }elseif($v['ct_code'] == $data['o_spouse_card']){
                $v['ct_attach']['auth'] = $data['o_spouse_auth'];
            }elseif(!empty($data['o_guarantor_auth'])){
                $count = count($data['o_guarantor_auth']);
                for($i = 0;$i < $count;$i++){
                    if($v['ct_code'] == $data['o_guarantor_card'][$i]){
                        $v['ct_attach']['auth'] = $data['o_guarantor_auth'][$i];
                    }
                }
            }
            try{
                $model->update('order_cert',array('ct_attach' => serialize($v['ct_attach'])),array('`ct_id` =?' =>$v['ct_id']));
            }catch (Exception $ex) {
            return array('success' => false, 'msg' => '保存异常');
            }
        }
        //状态修改
        $model->beginTransaction();
        try{
            $order_data = array(
                    'o_status' => '征信提交',
                    'o_quit_status' => $order_row['o_status'],
                    'o_trial_status' => '未审核',
                    'o_layer_status' => '未审核',
                    'o_review_status' => '未复核',
                    'o_videoaudit_status' => '未审核',
                    'o_videoaudit_time' => 0,
                    'o_first_time' => 0,
                    'o_first_atime' => 0,
                    'o_finishs_time' => 0,
                    'o_finishe_time' => 0,
                    'o_layer_aucode' => '',
                    'o_suspend_status' => 0,
                    'o_sell_time' => NOW_TIME,
                    'o_search_time' => 0
                );
            $cert_list = $model->getList('order_cert','*',array('`ct_oid` =?'=>$oid,'`ct_status` =?' =>'ok'));
            foreach($cert_list as $k => $v){
                $cert_data = array(
                    'ct_remark' =>'',
                    'ct_results' => '未查询',
                    'ct_querytime' => 0,
                    'ct_dateline' => NOW_TIME,
                    'ct_previous_remark' => $v['ct_remark'],
                    'ct_previous_querytime' => $v['ct_querytime']
                );
                $model->update('order_cert',$cert_data,array('`ct_id` =?'=>$v['ct_id']));
            }
            $model->update('order',$order_data, array('`o_id` = ?' => $oid));
            $log_data = array(
                'log_uid' => $member_info['u_id'],
                'log_action' => 'orderback',
                'log_related_id' => $oid,
                'log_explain' => '征信超时退回到征信提交',
                'log_dateline' => NOW_TIME,
            );
            $model->save('order_log', $log_data);
            $new_credit = $this->certList(array('`ct_oid` =?' =>$oid,'`ct_status`=?' =>'ok'));
            foreach($new_credit as $key => $val){
                $relation_arr = array('vip' => '本人', 'spouse' => '配偶', 'guarantor' => '担保人');
                $credit_data = array(
                    'user_id' => $oid,
                    'bairong_validate' => 1,
                    'bank_name'=>$order_row['o_bank'],
                    'orderno' => '!ysjr' . substr((1000000000000 + $oid), 1, 12),
                    'master_name' => $data['o_vip_name'],
                    'custom_name' => $val['ct_name'],
                    'relation' => $relation_arr[$val['ct_key']],
                    'idtype' => '000',
                    'idno' => $val['ct_code'],
                    'mobile' => $val['ct_mobile'],
                    'pics' => array(
                        array(
                            'picid' => '0002',
                            'picurl' => StringCode::doUrlimage($val['ct_attach']['fcard']),
                        ),
                        array(
                            'picid' => '0003',
                            'picurl' => StringCode::doUrlimage($val['ct_attach']['rcard']),
                        ),
                        array(
                            'picid' => '0001',
                            'picurl' => StringCode::doUrlimage($val['ct_attach']['auth']),
                        ),
                        array(
                            'picid' => '0004',
                            'picurl' => StringCode::doUrlimage($val['ct_attach']['sign']),
                        ),
                    ),
                );
                $x = \yii2api\classes\yii2api\Bank::submitCredit($credit_data);
                if ($x->msg_code == '2001') {
                    //请将上一次的征信结果，直接保存order_cert表
                }
                if ($x->msg_code == '2002') {
                    $model->update('order_cert', array('ct_remark' => '银行灰名单客户', 'ct_results' => '已查询'), array('`ct_id` = ?' => $val['ct_id']));
                }
            }

            $model->commit();
            return array('success' => true, 'msg' => '退回成功');
        }catch (Exception $ex) {
            $model->rollBack();
            return array('success' => false, 'msg' => '出现异常' . $ex->getMessage());
        }

    
    }


    /**
     * 紧急联系人信息验证(紧急联系人不能与主贷同名，同手机号，关系不能为本人)
     * @param $contact_msg 紧急联系人信息
     * @param $o_id 订单号
     * @param $ot_mobile 主贷人手机
     * @return type
     */
    public function contactcheck($contact_msg=array(),$oid,$ot_mobile){
        if(empty($contact_msg) || empty($oid)) return false;
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order','*',array('`o_id` =?' => $oid));
        foreach($contact_msg as $k=>$v){
            foreach($v as $x=>$y){
                $contact_msg[$k][$x] = trim($y," ");
            }
        }
        if($order_row['o_vip_name'] == $contact_msg[0]['name'] || $order_row['o_vip_name'] == $contact_msg[1]['name'] || $contact_msg[0]['name'] == $contact_msg[1]['name']){
            return array('success' => false,'msg' => '紧急联系之间或主贷人之间不能同名');
        }
        if($ot_mobile == $contact_msg[0]['mobile'] || $ot_mobile == $contact_msg[1]['mobile'] || $contact_msg[1]['mobile'] == $contact_msg[0]['mobile']){
            return array('success' => false,'msg' => '紧急联系之间或主贷人之间不能同手机号');
        }
        if($contact_msg[0]['relation'] == '本人' || $contact_msg[1]['relation'] == '本人'){
            return array('success' =>false ,'msg' =>'请选择正确的紧急联系人关系');
        }
        return array('success' => true,'msg' =>'信息合规');
    }

    /**
     * 获取与订单电审占位人员同等级的审核员(不包括当前占位人员)
     * @param $oid 订单号
     * @return type
     */
    public function getSameLevelAuditor($oid){
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order','*',array('`o_id` =?' =>$oid));
        $member_msg = $model->getOneRow('member','*',array('`u_id` =?' => $order_row['o_final_perch']));
        $member_arr = $model->getList('member','*',array('`u_auditlevel` =?' => $member_msg['u_auditlevel'],'`u_status` =?' =>'ok','`u_id` != ?' =>$member_msg['u_id']));
        return $member_arr; 
    }

    /**
     * 修改电审占位人并判断是否清空电审开始时间
     * @param $oid 订单号
     * @param $o_final_perch 占位人ID
     * @return type
     */
    public function replaceTelAuditor($oid,$o_final_perch){
        if(empty($oid) || empty($o_final_perch)) return false;
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order','*',array('`o_id` =?' =>$oid));
        try{
            $up_date = empty($order_row['o_layer_aucode'])? array('o_telstart_time' =>0,'o_final_perch' =>$o_final_perch) : array('o_final_perch' =>$o_final_perch);
            $model->update('order',$up_date,array('`o_id` =?' => $oid));
            return array('success' => true, 'msg'=>'保存成功');
        }catch (Exception $ex) {
            return array('success' => false, 'msg' => '出现异常' . $ex->getMessage());
        }
    }

    /**
     * 记录首次成功下载的用户和时间,作为“出报告人”和“出报告时间”保存
     * @param $oid 订单号
     * @param $u_id 用户号
     * @return type
     */
    public function exportReport($oid,$u_id){
        if(empty($oid) || empty($u_id)) return false;
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order','*',array('`o_id` =?' => $oid));
        if($order_row['o_report_downtime'] == 0){
            $member_row =$model->getOneRow('member','*',array('`u_id` =?' => $u_id));
            $up_date = array(
                'o_report_downtime' => NOW_TIME,
                'o_report_downuser' => $member_row['u_realname']
            );
            try{
                $model->update('order',$up_date,array('`o_id` =?' =>$oid));
                return array('success' => true,'msg' => '保存记录成功');
            }catch(Exception $ex) {
                return array('success' => false, 'msg' => '出现异常' . $ex->getMessage());
            }
        }
        return array('success' =>true ,'msg'=>'记录已经存在，非第一次下载');
    }

    //百融大数据unicode解析
    function unicodeDecode($unicode_str){
        $unicode_arr = explode("u", $unicode_str);
        foreach($unicode_arr as $k =>$v){
            if($k != 0){
                $unicode_arr[$k] = '\u'.$v;
            }
        }
        $unicode_str = implode('', $unicode_arr);
        $json = '{"str":"'.$unicode_str.'"}';
        $arr = json_decode($json,true);
        if(empty($arr)) return '';
        return $arr['str'];
    }
    /**
     * 资审自动占位
     * @param $oid 订单号
     * @return type
     */
    public function ftoPerch($oid){
        $model = $this->LoadModel('Public');
        $audit_msg = $model->getRow('order_audit','*',array('`a_oid` =?' =>$oid,'`a_type` =?' =>'初审审核','`a_status` =?' =>'ok'),null,array('a_id DESC'));
        if(!empty($audit_msg)){
            $data = array(
                'o_perch' => $audit_msg['a_uid'],
                'o_perch_name' => $audit_msg['a_uname']
            );
        }else{
            $member_msg = $model->getRow('member','*',array('`u_role` =?' => 7,'`u_status` =?' =>'ok'),null,array('u_order_count ASC'));
            $data = array(
                'o_perch' =>$member_msg['u_id'],
                'o_perch_name' =>$member_msg['u_realname']
            );
            $model->update('member',array('u_order_count' =>$member_msg['u_order_count'] +1),array('`u_id` =?' =>$member_msg['u_id']));
        }
        return $data;
    }

    /**
     * 获取其他资审员
     * @param $oid 订单号
     * @return type
     */
    public function getOtherDataauditor($oid){
        if(empty($oid)) return array('success' =>false,'msg'=>'参数错误');
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order','*',array('`o_id` =?' =>$oid));
        $member_row = $model->getOneRow('member','*',array('`u_id` =?' => $order_row['o_perch']));
        $member_arr = $model->getList('member','*',array('`u_role` IN(?)' =>array(7,34),'`u_status` =?' =>'ok','`u_id` != ?' =>$member_row['u_id']));
        return $member_arr; 
    }


    /**
     * 替换资审人员
     * @param $oid 订单号
     * @param $perch 替换人员u_id与u_realname拼接
     * @return type
     */
    public function replaceDataAuditor($oid,$perch){
        if(empty($oid)) return array('success' =>false,'msg'=>'参数错误');
        $data = explode('_',$perch);
        $model = $this->LoadModel('Public');
        try{
            $model->update('order',array('o_perch' => $data[0],'o_perch_name' => $data[1]),array('`o_id` =?' => $oid));
            return array('success' => true, 'msg' => '替换成功');
        }catch(Exception $ex) {
            return array('success' => false, 'msg' => '出现异常' . $ex->getMessage());
        }
    }

    /**
     * 同一网点近两个月车型查重及汇总
     * @param $oid 订单号
     * @return type
     */
    public function carmodelCheck($oid){
        if(empty($oid)) return false;
        $model = $this->LoadModel('Public');
        $order_row = $model->getOneRow('order','*',array('`o_id` =?' => $oid));
        $car_row = $model->getOneRow('order_car','*',array('`ot_oid` =?' =>$oid));
        $condition = array(
            '`o_first_time` >?' => NOW_TIME -5184000,
            '`o_status` IN(?)' =>array('初审提交','审核中','终审通过'),
            '`o_branch_id` =?' =>$order_row['o_branch_id']
        );
        $order_list = $model->getList('order','*',$condition);
        $order_count = count($order_list);//两个月提交订单数
        if(!empty($order_list)){
            foreach($order_list as $k=>$v){
                if($v['o_id'] != $oid){
                    $oid_arr[$v['o_number']] = $v['o_id'];
                }
            }
        }
        $car_list = $model->getList('order_car','*',array('`ot_oid` IN(?)'=>$oid_arr,'`ot_car_model` =?' => $car_row['ot_car_model']));
        $car_arr = array();
        if(!empty($car_list)){
            foreach($car_list as $k=>$v){
                $car_arr[] = array_search($v['ot_oid'],$oid_arr);
            }
        }
        $order_car_count = count($car_arr);//相同车型的单数
        $data['order_count'] = $order_count;
        $data['car_arr'] = $car_arr;
        $data['car_count'] = $order_car_count;
        return $data;
    }

    /**
     * 主贷人公司名查重
     * @param $oid 订单号
     * @return type
     */
    public function companyCheck($oid){
        if(empty($oid)) return false;
        $model = $this->LoadModel('Public');
        $owner_row = $model->getOneRow('order_owner','*',array('`ot_oid` =?' =>$oid));
        if(strlen($owner_row['ot_company'])>15){//大于五个中文字才查重
            $owner_list = $model->getList('order_owner','*',array('`ot_company` =?' =>$owner_row['ot_company'],'`ot_oid` != ?' =>$oid));
            if(!empty($owner_list)){
                foreach($owner_list as $k=>$v){
                    $oid_arr[] = $v['ot_oid']; 
                }
            }
            $order_list = $model->getList('order','*',array('`o_id` IN(?)' =>$oid_arr,'`o_status` IN(?)' => array('初审提交','审核中','终审通过'),'`o_first_time` >?' =>NOW_TIME-31536000));
            if(!empty($order_list)){
                foreach($order_list as $x=>$y){
                    $same_data[] = $y['o_number'];
                }
            }
            $count = count($order_list);
            $data['count'] = $count;
            $data['same_data'] = $same_data;
        }else{
            $data['count'] = 0;
        }
        return $data;
    }
}
